java – ListView, remember / restore scroll position

Question:

How to remember the scroll position of the ListView and restore them the next time you return to the activity with it?

Answer:

Personally, I think the following method is the most optimal (suitable for rotating the device and navigating the stack within one application launch):

Parcelable state;

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    listView.setAdapter(adapter);
    ...
    if(state != null) {
        listView.onRestoreInstanceState(state);
    }
}

@Override
public void onPause() {    
    state = listView.onSaveInstanceState();
    super.onPause();
}

That is, we use methods for saving and restoring the state of the list, which are specially designed for this.

If long-term storage is required (for example, remember the position after exiting the application), then you can use the following method:

SharedPreferences pref;

@Override
public void onResume() {
    super.onResume();

 pref = PreferenceManager.getDefaultSharedPreferences(this);
 mList.setSelectionFromTop(pref.getInt("index",0), pref.getInt("top",0));
}

@Override
public void onPause() {   

    int index = mList.getFirstVisiblePosition();
    View v = mList.getChildAt(0);
    int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());

    pref = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit = pref.edit();
    edit.putInt("index", index);
    edit.putInt("top", top);
    edit.apply();

    super.onPause();
}

That is, here, before exiting the activity, we get the position in which the ListView is located and save it in SharedPrefrences for long-term storage, then restore the saved position in the list when (re-) starting the activity.

Other solutions enSO

Scroll to Top