Android Spinner в Listview иногда переинициализируется - PullRequest
0 голосов
/ 11 января 2012

Я создал адаптер в Android:

public class PointVerificationAdapter extends BaseAdapter {
    List<PointVerification> mObjects;
    Context mContext;
    LayoutInflater mInflater;
    Dao<ChoixPointVerification, Integer> mChoixPointVerificationDao;
    HashMap<Integer, ReponsePointVerification> mReponses;

public PointVerificationAdapter(Context context,
        Dao<ChoixPointVerification, Integer> choixPointVerificationDao,
        List<PointVerification> ListePointsVerification,
        HashMap<Integer, ReponsePointVerification> listeReponsesPointsVerification) {
    mInflater = LayoutInflater.from(context);
    this.mContext = context;
    this.mObjects = ListePointsVerification;
    this.mChoixPointVerificationDao = choixPointVerificationDao;
    this.mReponses = listeReponsesPointsVerification;
}

@Override
public int getCount() {
    return mObjects.size();
}

@Override
public PointVerification getItem(int position) {
    return mObjects.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row;

    if (null == convertView) {
        row = mInflater.inflate(R.layout.intervention_reponses_list, null);
    } else {
        row = convertView;
    }

    // affichage du nom du point de vérification
    TextView tv = (TextView) row.findViewById(R.id.tvNom);
    tv.setText(getItem(position).nom);

    Integer idChoixPointVerification = null;
    Integer idPointVerification = getItem(position).id;
    if (mReponses != null && mReponses.containsKey(idPointVerification)) {
        // affichage du commentaire
        if (mReponses.get(idPointVerification).commentaire != null)
        {
            EditText edCommentaire = (EditText) row.findViewById(R.id.edCommentaire);
            edCommentaire.setText(mReponses.get(idPointVerification).commentaire);
        }

        idChoixPointVerification = mReponses.get(idPointVerification).idChoixPointVerification;
    }



    // affichage de la liste déroulante
    Spinner spi = (Spinner) row.findViewById(R.id.spiListeChoix);
    ChoixPointVerificationDal choixPointVerificationDal = new ChoixPointVerificationDal();
    List<ChoixPointVerification> listeChoixPointVerification;
    try {
        listeChoixPointVerification = choixPointVerificationDal
                .GetByIdPointVerification(mChoixPointVerificationDao,
                        getItem(position).id);

        List<String> pointVerifications = new ArrayList<String>();
        for(ChoixPointVerification choixPointVerification: listeChoixPointVerification)
        {
            pointVerifications.add(choixPointVerification.nom);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item,
                pointVerifications);

        spi.setAdapter(adapter);

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return row;
}

Иногда, когда я прокручиваю список или открываю доступ к EditView, вызывается обратный вызов GetView, поэтому спиннер повторно инициализируется, и я теряю выбор пользователя.Есть ли решение для этого?

Edit

хорошо, я чувствую, что GetView действительно вызывается очень часто, и я не должен перезапускать Spinner каждый раз, когда он входит в эту функцию,Но как я могу определить, является ли это первым запуском этого кода?У меня был id магазин, в котором позиция была выбрана с чем-то вроде этого

        spi.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                varPosition = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });

, но я не думаю, что это хороший способ ...: (

Редактировать 2

Если я хочу создать спиннер с OnItemClickListener. Какая техника? На данный момент я делаю это:

public class PointVerificationAdapter extends BaseAdapter {
List<PointVerification> mObjects;
Context mContext;
LayoutInflater mInflater;
Dao<ChoixPointVerification, Integer> mChoixPointVerificationDao;
HashMap<Integer, ReponsePointVerification> mReponses;
Integer mPositionSelectionne;

public PointVerificationAdapter(
        Context context,
        Dao<ChoixPointVerification, Integer> choixPointVerificationDao,
        List<PointVerification> ListePointsVerification,
        HashMap<Integer, ReponsePointVerification> listeReponsesPointsVerification) {
    mInflater = LayoutInflater.from(context);
    this.mContext = context;
    this.mObjects = ListePointsVerification;
    this.mChoixPointVerificationDao = choixPointVerificationDao;
    this.mReponses = listeReponsesPointsVerification;
}

@Override
public int getCount() {
    return mObjects.size();
}

@Override
public PointVerification getItem(int position) {
    return mObjects.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row;

    if (null == convertView) {
        row = mInflater.inflate(R.layout.intervention_reponses_list, null);
    } else {
        row = convertView;
    }

    // affichage du nom du point de vérification
    TextView tv = (TextView) row.findViewById(R.id.tvNom);
    tv.setText(getItem(position).nom);

    Integer idPointVerification = getItem(position).id;
    if (mReponses != null && mReponses.containsKey(idPointVerification)) {
        // affichage du commentaire
        if (mReponses.get(idPointVerification).commentaire != null) {
            EditText edCommentaire = (EditText) row
                    .findViewById(R.id.edCommentaire);
            edCommentaire
                    .setText(mReponses.get(idPointVerification).commentaire);
        }

    }

    // affichage de la liste déroulante
    Spinner spi = (Spinner) row.findViewById(R.id.spiListeChoix);
    spi.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            View row = mInflater.inflate(R.layout.intervention_reponses_list, null);

            ChoixPointVerificationDal choixPointVerificationDal = new ChoixPointVerificationDal();
            List<ChoixPointVerification> listeChoixPointVerification;
            try {
                listeChoixPointVerification = choixPointVerificationDal
                        .GetByIdPointVerification(mChoixPointVerificationDao,
                                getItem(position).id);

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
                        android.R.layout.simple_spinner_dropdown_item,
                        pointVerifications);

                spi.setAdapter(adapter);

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });



    return row;

}

Редактировать 3

Макет действия, содержащего просмотр списка

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

    <ListView
        android:id="@+id/lstPointsVerification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >
    </ListView>

</LinearLayout>

И просмотр списка для каждой строки просмотра списка

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">

  <TextView
    android:id="@+id/tvNom" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
android:layout_weight="1"
    style="@style/ListePrincipal"
  />

   <Spinner
      android:id="@+id/spiListeChoix"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1" />


  <EditText
    android:id="@+id/edCommentaire" 
        android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    style="@style/ListePrincipal"
  />
</LinearLayout>

Моя цель - создать список точек для проверкипользователем. У него будет около 20 строк для проверки. Каждая строка содержит метку, счетчик с выбором разницы и поле комментария. Затем мне придется получать каждый ответ в каждой строке.

1 Ответ

1 голос
/ 11 января 2012

Вот пример OnItemClick для просмотра списка.Вы должны переместить свое создание блесны в другом месте, а не в отдельный метод.Затем вызовите его при щелчке элемента, как это сделано здесь

ListView mainListview = new ListView(this);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_single_choice,  new String[]{"Search","Options"});
            mainListview.setAdapter(adapter); /// your adapter here
            mainListview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {

        ///doYourSpinnerStuff(arg1) here

                    }

                            });

Весь этот фрагмент кода ниже должен быть перемещен в другое место, а не в отдельный метод.Затем вы создаете счетчик, а затем заполняете его одним щелчком мыши.Можете ли вы показать эскиз - скриншот или макет, как вы хотите разместить свои виды в вашей деятельности.

// affichage de la liste déroulante
    Spinner spi = (Spinner) row.findViewById(R.id.spiListeChoix);
    ChoixPointVerificationDal choixPointVerificationDal = new ChoixPointVerificationDal();
    List<ChoixPointVerification> listeChoixPointVerification;
    try {
        listeChoixPointVerification = choixPointVerificationDal
                .GetByIdPointVerification(mChoixPointVerificationDao,
                        getItem(position).id);

        List<String> pointVerifications = new ArrayList<String>();
        for(ChoixPointVerification choixPointVerification: listeChoixPointVerification)
        {
            pointVerifications.add(choixPointVerification.nom);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item,
                pointVerifications);

        spi.setAdapter(adapter);

    } catch (SQLException e) {
        e.printStackTrace();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...