Reputation: 839
I'm now developing an application that uses a ListView with a CheckedTextView on every item that managed by an ArrayAdapter to support multiple chooses. The contents in my ListView are dynamic, that means, can be changed during runtime. Now I try to use ListView.getCheckedItemPositions() to get all checked items, Because I want to save all the checked positions and auto-check them when user go back to this page again. So I need to save checked results for every page.
For the first page everything works fine as expected. But when user goes to another page and make some chooses, the result array that ListView returned contains some positions that are never checked. I don't why ListView has this strange behavior. Even for a page that in fact no checked happens but ListView gives me a result that indicates there's one item has been checked.
could anyone who can teach me how to get the position of CheckedTextView in its OnClickListener callback?
example code is appreciate.
Thanks in advance...
Upvotes: 0
Views: 2063
Reputation: 10810
The listview recycles its views so when you go to a different page and then return to the previous page, the listview recalls the getView() function for its views. To make sure that the order of the checked views are not mixed up, create an arraylist that contains the check state of all the views before initializing the adapter. Then pass the arraylist as an argument for the adapter's constructor. There, in the getView() function, set the checked state of each checkable textview based on the arraylist. Then, return to the activity class and override the onItemClick() event. Using the view that is given to you when the function is called, do the following to get the checkable textview and set its checked state:
listView1.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View selectedView, int position , long id)
{
CheckedTextView tv = (CheckedTextView)selectedView.findViewById(R.id.textview);
if (tv.isChecked())
{
tv.setChecked(false);
checkStatesOfViews.get(position) = false;
}
else
{
tv.setChecked(true);
checkStatesOfViews.get(position) = true;
}
} });
Upvotes: 3