Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain the position of ListView [duplicate]

Tags:

android

Possible Duplicate:
Maintain/Save/Restore scroll position when returning to a ListView

How can I maintain the position of my ListView in my activity when I go to another activity (by launching another intent) and then come back (press the back button)?

Thank you.

like image 397
michael Avatar asked Apr 27 '10 20:04

michael


2 Answers

Declare global variables:

int index = 0;
ListView list;

and make a reference to your ListView in onCreate():

list = (ListView) findViewById(R.id.my_list);

Next, in onResume(), add this line at the end:

list.setSelectionFromTop(index, 0);

Lastly, in onPause, add the following line to the end:

index = list.getFirstVisiblePosition();
like image 105
Phil Avatar answered Oct 10 '22 01:10

Phil


Do simple....

@Override
protected void onPause()
{
   index = listView.getFirstVisiblePosition();
   // store index using shared preferences   
}

and..

@Override
public void onResume() {
super.onResume();
// get index from shared preferences

if(listView != null){
    if(listView.getCount() > index)
        listView.setSelectionFromTop(index, 0);
    else
        listView.setSelectionFromTop(0, 0);
}
like image 26
Rajeev Mathur Avatar answered Oct 10 '22 00:10

Rajeev Mathur