我的代码设计为listview中的单个项目有两个复选框,问题是当我点击第一个复选框时,另一个复选框被自动点击,当我取消选中其中一个时另一个复选框未经自动取消选中
我认为问题在于两个复选框得到了项目的位置,所以它们具有相同的位置,我需要每个复选框都有它自己的位置
@Override public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
View itemView = convertView;
if (itemView == null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.textView1 = (TextView) itemView.findViewById(R.id.textView1);
holder.check1 = (CheckBox) itemView.findViewById(R.id.check1);
holder.check2 = (CheckBox) itemView.findViewById(R.id.check2);
itemView.setTag(holder);
}
else{
holder = (ViewHolder) itemView.getTag();
}
holder.check1.setTag(position);
final Item item = items.get(position);
holder.textView1.setText(item.getName());
holder.check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(buttonView.isPressed()){
if (position != ListView.INVALID_POSITION) {
Item p = items.get(position);
p.setSelected(isChecked);
}
}
}
}
);
holder.check2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(buttonView.isPressed()){
if (position != ListView.INVALID_POSITION) {
Item p = items.get(position);
p.setSelected(isChecked);
}
}
}
}
);
holder.check1.setChecked(item.isSelected());
holder.check2.setChecked(item.isSelected());
return itemView;
}
}private static class ViewHolder {
public TextView textView1;
public CheckBox check2,check1;
}}
答案 0 :(得分:0)
原因是check1
和check2
使用相同的值
holder.check1.setChecked(item.isSelected());
holder.check2.setChecked(item.isSelected());
因此,在Item
类中,您应声明2个变量(如isSelectedCheck1和isSelectedCheck2)以保存状态为2复选框