Android ListView With Toggle Button
I'm having a problem when my ListView has more itens that can appear on the screen; in other words, when it gets scroll. The problem is, when I click in one of the toggle buttons,
Solution 1:
Your issue is due to the recycling of Views in ListView
(and RecyclerView
) The following happens to you:
- You set visibility of an
ImageView
in one row to invisible with yourToggleButton
- Your row gets scrolled out of sight and therefore gets recycled.
- The recycled view still has an
ImageView
with visilibility set toView.INVISIBLE
- You assign your new values to the row but don't change the visibility
To solve this you should have a List
, HashMap
or anything similar and track which ToggleButton
is checked and which ImageView
is visible. (You can do that with the position)
Then in your public View getView(int position, View convertView, ViewGroup parent)
method you check if this posision's (rows) image should be visible or not and set it accordingly with viewHolder.btnCam.setVisibility()
and the ToggleButton
as well.
EDIT
Add this member variable to your adapter
HashMap<Integer,Boolean> toggleButtonStateTracker = new HashMap<>;
In your getView add this
if (! toggleButtonStateTracker.containsKey(position)){
// Now the HashMap definitely contains the key
toggleButtonStateTracker.put(position,false);
}
boolean isChecked = toggleButtonStateTracker.get(position);
viewHolder.tgIrregular.setChecked(isChecked);
if (isChecked){
// if your toggle Button is checked, the btnCam should be invisible
viewHolder.btnCam.setVisibility(View.INVISIBLE);
} else {
viewHolder.btnCam.setVisibility(View.VISIBLE);
}
And finally add this tgIrregular
viewHolder.tgIrregular.setOnCheckedChangedListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toggleButtonStateTracker.put(getAdapterPosition, isChecked);
}
});
Post a Comment for "Android ListView With Toggle Button"