I have a ListActivty
with listview choice mode set to CHOICE_MODE_SINGLE
The item layout contains only a CheckedTextView
. By default when the activity is shown all items are unchecked. If the user clicks on an item it is automatically getting checked and check-mark is shown. Clicking another item unchecks the previous item. All this is working out of the box.
What I want to do is to uncheck an item of the user clicks on an already checked item. I have overridden onListItemClick
method to detect if the item is already checked and uncheck it like this:
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
CheckedTextView checkedTextView = (CheckedTextView) view;
if (checkedTextView.isChecked()) {
listView.setItemChecked(position, false);
}
}
The problem is that on Android 4.4 checkedTextView.isChecked()
always returns true: if I click on an unchecked item it returns true and clicking on checked item returns true as well. I have tried listview.isItemChecked(position)
but it works the same way.
Is there any other way to detect that I have clicked on a checked item so that I can uncheck it?
KitKat AbsListView
is notifying the listener after handling the click, thus it is already checked when you call checkedTextView.isChecked()
in your listener.
Try creating your custom ListView which overrides performItemClick()
, save the item state before the super call and act upon it aftewards like this (untested):
@Override
public boolean performItemClick(View view, int position, long id) {
boolean checkedBeforeClick = isItemChecked(position);
super.performItemClick(view, position, id);
if (checkedBeforeClick) {
setItemChecked(position, false);
}
}