[英]Handle checked and then unchecked checkbox's value in listview android
In my activity I have 4 items in a list view with checkboxes in each row. 在我的活动中,列表视图中有4个项目,每行都有一个复选框。 After I leave activity I want all the checked item position numbers in an arraylist.
离开活动后,我希望所有选中的项目位置编号都在arraylist中。 This code works fine when user clicks all the checkboxes ones and leave the activity.
当用户单击所有复选框并退出活动时,此代码可以正常工作。 But when user clicks a checkbox and then unchecks it, item position is arraylist doesnt able to clear.
但是,当用户单击复选框然后取消选中该复选框时,arraylist的项目位置无法清除。 This methood is in my CustomAdapter class.
这种情况在我的CustomAdapter类中。
class GameAdapter extends BaseAdapter{
private ArrayList<Integer> positions = new ArrayList<Integer>();
public ArrayList<Integer> getPositions() {
return positions;
}
getView(....){
final ViewHolder holder;
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(holder.checkBox.isChecked()) {
positions.add(position);
}
}
});
}
}
I am handling this adapter class in the activity where my listview resides. 我在我的listview所在的活动中处理此适配器类。 There I am taking this arraylist values like this
我在这里采用这样的arraylist值
ArrayList<Integer> gamePositions = mGameAdapter.getPositions();
String itemNumbers = gamePositions.toString();
in itemNumber string I want all the checked item number values. 在itemNumber字符串中,我需要所有检查的项目编号值。
Thank you in advance for guidance.... 预先感谢您的指导。
Follow below approach. 请遵循以下方法。
Use HashMap instead of Arraylist, like below 使用HashMap代替Arraylist,如下所示
HashMap<Integer,Boolean> mapOfSelection = new HashMap<>();
before onClick
method, assign position
to the checkbox, like below. 在
onClick
方法之前,将position
分配给复选框,如下所示。
holder.checkbox.setTag(position);
In onClick, do the following. 在onClick中,执行以下操作。
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mapOfSelection.put((Integer)buttonView.getTag(),isChecked); // True if this position/value is checked, false otherwise. }
Now when you need the selected items, just loop through the hashmap and check the positions/Key
which have True
value. 现在,当您需要选定的项时,只需遍历哈希图并检查具有
True
值的positions/Key
。
Replace this 取代这个
if(holder.checkBox.isChecked()) {
positions.add(position);
}
with this 有了这个
if(holder.checkBox.isChecked()) {
if(!positions.contains(position))
positions.add(position);
} else {
if(positions.contains(position))
positions.remove(position);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.