I have a long ListView
that the user can scroll around before returning to the previous screen. When the user opens this ListView
again, I want the
If you are saving/restoring scroll position of ListView
yourself you are essentially duplicating the functionality already implemented in android framework. The ListView
restores fine scroll position just well on its own except one caveat: as @aaronvargas mentioned there is a bug in AbsListView
that won't let to restore fine scroll position for the first list item. Nevertheless the best way to restore scroll position is not to restore it. Android framework will do it better for you. Just make sure you have met the following conditions:
setSaveEnabled(false)
method and not set android:saveEnabled="false"
attribute for the list in the xml layout fileExpandableListView
override long getCombinedChildId(long groupId, long childId)
method so that it returns positive long number (default implementation in class BaseExpandableListAdapter
returns negative number). Here are examples:.
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0L | groupPosition << 12 | childPosition;
}
@Override
public long getCombinedChildId(long groupId, long childId) {
return groupId << 32 | childId << 1 | 1;
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getCombinedGroupId(long groupId) {
return (groupId & 0x7FFFFFFF) << 32;
}
ListView
or ExpandableListView
is used in a fragment do not recreate the fragment on activity recreation (after screen rotation for example). Obtain the fragment with findFragmentByTag(String tag)
method.ListView
has an android:id
and it is unique.To avoid aforementioned caveat with first list item you can craft your adapter the way it returns special dummy zero pixels height view for the ListView
at position 0.
Here is the simple example project shows ListView
and ExpandableListView
restore their fine scroll positions whereas their scroll positions are not explicitly saved/restored. Fine scroll position is restored perfectly even for the complex scenarios with temporary switching to some other application, double screen rotation and switching back to the test application. Please note, if you are explicitly exiting the application (by pressing the Back button) the scroll position won't be saved (as well as all other Views won't save their state).
https://github.com/voromto/RestoreScrollPosition/releases