How to save and restore ListView position in Android

Avinash picture Avinash · Aug 23, 2011 · Viewed 18.1k times · Source

I have tabView, displaying list in each tab. When I scroll in one tab, switch to another tab and return to previous tab, position is returned to the top instead of displaying previous scrolled position. How do I achieve this ? Need to know how do I use onSaveInstanceState & onRestoreInstanceState to save position and use the saved position in displaying the previous scrolled position.

Thanks in Advance.


Thanks all for your reply. I tried with all the solutions but ran into other issues. Basically the problem i am facing is as follows.

I have a listview as my first activity when I launch my app. When I click on the list item, it launches the tab activity containing 3 tabs. All 3 tabs uses the same activity called ListActivity. But 3 tabs contains different data. My question is how to retain the position of the list when I switch between the tabs. With the above solutions provided, when I change the position in one tab, it affects the remaining tabs as well. For example, if I am at position 6 in first tab, this position will be set for second and third tab as well as I am using the same ListActivity for all 3 tabs. I am not allowed to share the code. So have to type the problem this long. Also number of tabs created are dynamic. It might be 3 or 4 or 5. But all tabs use 1 ListActivity.

Can anyone give me a example how to achieve this. 1. Single ListActivity used in multiple tabs. 2. Retaining the cursor position in tabs without after affecting other tabs.

Your solution provided is appreciated. Thanks in advance.

Answer

b_yng picture b_yng · Aug 23, 2011

Don't call setAdapter() again on the list view. Do something like this.

if(myListView.getAdapter() == null)
    myListView.setAdapter(new myAdapter(this, R.layout.row, items));

If you need to update your ListView call notifyDataSetChanged() on the adapter.