In my activity I have 4 items in a list view with checkboxes in each row. After I leave activity I want all the checked item position numbers in an 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. This methood is in my CustomAdapter class.
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. There I am taking this arraylist values like this
ArrayList<Integer> gamePositions = mGameAdapter.getPositions();
String itemNumbers = gamePositions.toString();
in itemNumber string I want all the checked item number values.
Thank you in advance for guidance....
Follow below approach.
Use HashMap instead of Arraylist, like below
HashMap<Integer,Boolean> mapOfSelection = new HashMap<>();
before onClick
method, assign position
to the checkbox, like below.
holder.checkbox.setTag(position);
In onClick, do the following.
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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.