Home » Android » android – How to maintain the position of ListView

android – How to maintain the position of ListView

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&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();

Answer:

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);
}

Answer:

You should use onSaveInstanceState to store the scroll position and then use either onCreate or onRestoreInstanceState to restore it.

http://developer.android.com…#onSaveInstanceState

Answer:

Please note that using ListView.getScrollY() DOES NOT WORK WELL for restoring the scroll position.

See Android: ListView.getScrollY() – does it work?

It is referring to the scroll amount of the entire view, so it will almost always be 0.

It happened to me too most of the time that this value was 0.
ListView.getFirstVisiblePosition() with ListView.setSelection() works more reliably.

Answer:

@Override
protected void onPause()
{
    // Save scroll position
    SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0);
    SharedPreferences.Editor editor = preferences.edit();
    int scroll = mListView.getScrollY();
    editor.put("ScrollValue", scroll);
    editor.commit();
}

@Override
protected void onResume()
{
    // Get the scroll position
    SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0);
    int scroll = preferences.getInt("ScrollView", 0);
    mListView.scrollTo(0, scroll);
}