Is there a way to check an element in a gridview
?
I cannot find the toggle()
method or setChecked(true)
, my gridview
has an adapter that extends BaseAdapter and I want to change background color when an element is checked (not only selected).
I would do like ListView: GridView.setChoicheMode(MULTICHOICE)
and then item.toggle()
or item.setChecked(true)
and store the state of check into the view.
Edit:
I added an empty CheckedTextView
to store the check state.
But is there a cleaner way to do this?
Edit2 Now I can do what I want but when i scroll down the gridview and then I scroll up the selected items aren't selected anymore.
boolean checked = layout.getCheckedItemPositions().get(position);
if(checked){
check.toggle();
view.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
else{
check.toggle();
view.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
}
where layout is the layout of the gridview. I think I have to modify the getView method of my adapter, but this code does not works:
CheckedTextView check = (CheckedTextView) layout.findViewById(R.id.txv_grid_check);
boolean checked = check.isChecked();
if(checked){
layout.setBackgroundColor(c.getResources().getColor(android.R.color.holo_green_light));
}
else{
layout.setBackgroundColor(c.getResources().getColor(android.R.color.transparent));
}
Edit 3
I think there is no way to do what I want (store the state in the CheckedTextView element) because the views are destroyed and recreated when scrolling a list or a gridview. So I needed to handle the state of the items into the adapter. I used an HashSet of int to store the position of the checked items and I made some public method for handle this list from the gridview. In the gridview activity it is possibile to get the adapter and then do myadapter.check(int position) or uncheck(int position). Then in the adapter, into the getView() method, we need to check if a position is in the list and set the appropriate background color.