1

Let's say I have a PreferenceActivity (which I cannot convert to use Fragments for compatibility reasons). One setting within that PreferenceActivity is for the current application theme, which I would like to apply instantly when changing the preference by calling PreferenceActivity#recreate() to force recreating the activity (using the new theme).

Unfortunately, the activity contains so many settings that scrolling may be required. Upon recreating the activity, I would like to restore the previous scroll position to allow for a seamless transition from one theme to another.

Attemting to preserve the embedded ListView's scroll position using getListView().getScrollY() in onSaveInstanceState, however, always returns zero.

Is there any way to get hold of the PreferenceActivity's list scroll position and to restore it later on?

Thilo-Alexander Ginkel
  • 6,679
  • 9
  • 40
  • 56

1 Answers1

2

First, you need to get 2 values:

final int firstVisibleItem = getListView().getFirstVisiblePosition();
final int firstVisibleItemTop = getListView().getChildAt(0).getTop();

Then save them into some storage (Preferences or Intent's budle or somewhere else). To restore scroll position from those values:

final ListView listView = getListView();
listView.setSelection(firstVisibleItem);
listView.smoothScrollBy(-firstVisibleItemTop, 0);
Denis Gladkiy
  • 1,823
  • 1
  • 23
  • 37