Checkbox in Spinner adapter is automatically checked when I scroll it

前端 未结 1 902
自闭症患者
自闭症患者 2020-12-22 11:19

What I have: I have a spinner, foe which I have set the adapter, the adapter displayed in coed below has a checkbox and a textview

相关标签:
1条回答
  • 2020-12-22 11:58

    this is due to the recycling of views in spinner,what you can do is declare an boolean array private ArrayList<Boolean> checked = new ArrayList<Boolean>(); and initialize in your adapter constructor

    for (int i = 0; i < this.getCount(); i++) 
     {
     checked.add(i, false);
     }
    

    and now your get view method use it like this:-

    your_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
            @Override
            public void onCheckedChanged(CompoundButton checkbox,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                 if (isChecked)
                 {
                 checked.set(position,true);
                 }
                 else
                 { 
                 checked.set(position,false);
                 }  
            }
        });
        your_checkbox.setChecked(your_data.get(position));
    

    and please use viewholder, its a good practice.

    0 讨论(0)
提交回复
热议问题