PRC
PRC

Reputation: 153

Losing current selection of list item after updating the listview items using notifyDataSetChanged

I need to refresh the ListView items every second, and it works fine using notifyDataSetChanged(). After the refresh, the already selected item in the list is losing its selection. ie, it loses its selected item background. How can I maintain the selected state of already selected item, after each refresh?

Thanking u for the support in advance.

Upvotes: 2

Views: 5418

Answers (2)

Lalit Poptani
Lalit Poptani

Reputation: 67286

As I understood your question your query is that you are losing the selected item focus of the ListView after refreshing the ListView. So, for that you can use ListView's setSelection() method to set the selected item in the ListView. So, when you refresh the ListView after that you can set the item that you want to be selected or the previous selected using setSelection().

listView.setSelection(position)

Here position is the position that was the last selected index before notifyDataSetChanged()

Upvotes: 3

Dharmendra
Dharmendra

Reputation: 33996

Probably it seems the issue of Recycling .If you want to refresh your view on a time interval you can use notifyDataSetChanged(). But you have to maintain your state of the listview.

For example you select a second position and now when you scroll listview or refresh the adapter then the state of the selected position will gone.So you have to maintain a array for selected item's position so that in getView() method of the Listview you can check that weather the array contains the position or not.If array contains the position that means this item is selected so you can change the controls value according to it if array does not contains the value that means that item is not selected.

Also if you are using checkbox or radio or other for display selection of the List-view then you have to implement the events like for checkbox either checkbox.setOnCheckedChangeListener() or checkbox.setonClickListener() same as radio and in this event you have to maintain the array of the selected items.

First you have to check weather the array contains the selected position or not? If not contains then add that position in the array and if yes then just remove that position from the array and refresh the adapter.

Upvotes: 0

Related Questions