Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save and restore ListView position in Android

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.

like image 508
Avinash Avatar asked Aug 23 '11 21:08

Avinash


3 Answers

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.

like image 158
b_yng Avatar answered Oct 12 '22 00:10

b_yng


To get the current position of your ListView, you can call

int position = mCatchList.getFirstVisiblePosition();

Then once you navigate back to the tab with that ListView, you can call

mCatchList.setSelection(position);

It will depend on how your code is written to tell if the position will need to be added to the savedInstanceState, or however.

like image 33
hooked82 Avatar answered Oct 12 '22 00:10

hooked82


Override onSaveInstanceState to save the position, and set the position back in onRestoreInstanceState. The Bundle is sort of like a HashMap, (pseudo-code):

In onSaveInstanceState:

bundle.putInt("MyTabsPosition", getPosition());

Then in onRestoreInstanceState:

pseudo.setPosition(bundle.getInt("MyTabsPosition"));
like image 39
CrackerJack9 Avatar answered Oct 11 '22 23:10

CrackerJack9