在我的 android 应用程序中,我在 ListView 中显示手机的联系人列表,并在每行中显示一个用于选择联系人的复选框。但是当我选择特定行时,大约第十行也会自动被选中。我在下面给出我的代码,如果有人知道请帮助..
public class ContactsAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Contact> contacts;
public ContactsAdapter(Context context, ArrayList<Contact> contacts)
{
this.context = context;
this.contacts = contacts;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
final ViewHolder mHolder;
if (convertView == null)
{
// gridView = new View(context);
// get layout from mobile.xml
//gridView = inflater.inflate(R.layout.contact, null);
convertView = inflater.inflate(R.layout.contact, null);
mHolder = new ViewHolder();
mHolder.textName =(TextView) convertView.findViewById(R.id.name);
mHolder.textMobile =(TextView) convertView.findViewById(R.id.mobile);
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
convertView.setTag(mHolder);
));
}
else
{
mHolder = (ViewHolder) convertView.getTag();
mHolder.textSelector.setOnCheckedChangeListener(null);
}
mHolder.textMobile.setText(contacts.get(position).getMobile());
mHolder.textName.setText(contacts.get(position).getName());
mHolder.textSelector.setFocusable(false);
return convertView;
}
private class ViewHolder {
private TextView textMobile,textName;
private CheckBox textSelector;
}
@Override
public int getCount() {
return contacts.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
最佳答案
那是因为每次滚动时 ViewHolder 都会回收 View 我建议您在 ListItem 上使用 onCLick 而不是复选框
要克服这个问题声明一个 SparseBooleanArray
SparseBooleanArray sba=new SparseBooleanArray();//this should be global
然后在渲染后立即设置项目检查状态
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
mHolder.textSelector.setChecked(sba.get(position));
然后写一个onClickListener给你convertView,手动检查
convertView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mHolder.textSelector.setChecked(isChecked);
sba.put(position,isChecked); //storing the state
}
}
);
**Well Now the sba has list items checked and you can use that for further Actions**
关于java - Listview中的Android复选框自动选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710697/