hi i am using checkboxes with listview in android when i am scrolling listitem i am not getting the same checkboxes checked what are expected please help me in figuring out where i am wrong. when i select frst check box and scroll its give me second checkbox as checked and other output are also strange.here is my code
class base extends BaseAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
return price.size();
}
@Override
publ开发者_如何转开发ic Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
View v=arg1;
j=arg0;
LayoutInflater li=getLayoutInflater();
v=li.inflate(R.layout.listitem, null);
TextView txt=(TextView)v.findViewById(R.id.tv_name);
txt.setText(author.get(arg0));
TextView txt1=(TextView)v.findViewById(R.id.tv_description);
txt1.setText(price.get(arg0));
TextView txt2=(TextView)v.findViewById(R.id.txtv);
txt2.setText(title.get(arg0));
ImageView img=(ImageView)v.findViewById(R.id.iv_forward);
img.setImageBitmap(bit.get(arg0));
CheckBox check1=(CheckBox)v.findViewById(R.id.check);
if(check[j]!=null)
if(check[j]==true)
check1.setChecked(true);
else check1.setChecked(false);
check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg2) {
// TODO Auto-generated method stub
if(arg2==true)
// Toast.makeText(SimpleActivity.this,arg0+"", Toast.LENGTH_LONG).show();
check[j]= true;
else
check[j]=false;
}
});
return v;
}
}
please help.
Since you are recycling your views each time, the checkbox will have the same value as the previous view of the listview. What I would do is set the checkbox to false FIRST for every iteration and THEN figure out whether or not it should be checked:
check1.setChecked(false);
if(check[j]!=null && check[j]==true){
check1.setChecked(true);
}
I think that it's probably because the Adapter getView()
method is calling onCheckedChanged()
(only when reused Views are of opposite value). This leads to strange behaviour.
public View getView(int arg0, View arg1, ViewGroup arg2) {
if(check[j]==true) check1.setChecked(true); // will automatically call onCheckedChanged
else check1.setChecked(false); // if check1 was previously the opposite
}
You should perhaps cancel checkListener before changing values so:
public View getView(int arg0, View arg1, ViewGroup arg2) {
check1.setOnCheckedChangeListener(null); // first remove listener
//update values
if(check[j]==true) check1.setChecked(true); //no more side effect
else check1.setChecked(false);
//reinstall listener
check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
//your code.
}
}
I had the similar issue with ListView with CheckBox.Here you can find a complete solution to this issue.
精彩评论