Maintain ListView Position in Android Application

Published by Michael Carrano on January 23, 2014



A small and simple feature you can immediately add to your Android application is the functionality of maintaining the ListView position. When your user switches to a different Activity/Screen and then back to the ListView, they will not have to scroll through the ListView items again to get back to where they were.

Android Studio (as well as Eclipse) offers a few nice default templates via ADT to get you started with your application and I am going to assume you will be developing off the Master Detail flow template.

To add this functionality, all we need to do is add a few lines of code to our ListFragment.

public class MyListFragment extends ListFragment {

   /**
    * Stores the scroll position of the ListView
    */
    private static Parcelable mListViewScrollPos = null;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        // Restore the ListView position
        if (mListViewScrollPos != null) {
            getListView().onRestoreInstanceState(mListViewScrollPos);
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        
        // Save the ListView position
        mListViewScrollPos = getListView().onSaveInstanceState();
    }
}

By implementing the above code changes, you have just improve the usability of your Android application and I am sure your users will appreciate it. If you want to see this functionality in action, then take a look at the 7 Minute Workout Android application I have developed.

One small thing to note, I am not sure how this works if you have implemented an “infinite scroll” functionality in your application. If you know the answer, please comment on the results. However, I do not see why this method would not work.