在我的应用中,一个FragmentActivity
包含一个简单的ListFragment
,我想保存用户滚动到的位置。我按照以下步骤操作:
private int initialScrollPosition = 0;
private int initialScrollYOffset = 0;
@Override
public void onSaveInstanceState (Bundle outState) {
outState.putInt(SCROLL_POSITION, this.getListView().getFirstVisiblePosition());
View firstVisibleItemView = this.getListView().getChildAt(0);
outState.putInt(SCROLL_Y_OFFSET, (firstVisibleItemView == null) ? 0 : firstVisibleItemView.getTop());
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.restoreState(savedInstanceState);
}
private void restoreState(Bundle savedInstanceState) {
if(savedInstanceState != null
&& savedInstanceState.containsKey(SCROLL_POSITION)) {
this.initialScrollPosition = savedInstanceState.getInt(SCROLL_POSITION);
}
if(savedInstanceState != null
&& savedInstanceState.containsKey(SCROLL_Y_OFFSET)) {
this.initialScrollYOffset = savedInstanceState.getInt(SCROLL_Y_OFFSET);
}
}
@Override
public void onStart () {
super.onStart();
// some other GUI stuff
this.getListView().setSelectionFromTop(this.initialScrollPosition, this.initialScrollYOffset);
}
这个解决方案适用于像显示方向更改或从我的应用程序的一个 Activity
移动到下一个的情况。
但是,如果我打开应用程序,滚动一点,回到主页,然后从最近列表中恢复应用程序,则不会调用 onActivityCreated
(或任何其他具有 savedInstanceState
Bundle
的回调),因此无法恢复状态。
因此,我有两个问题:
- 如何在恢复时获得没有使用
onXXXCreated
回调的savedInstanceState
? - 生命周期确切地在做什么。我想了解为什么我的方法失败了。
非常感谢您提供的任何见解!
解决方案:
感谢André的建议!我将我的 onSaveInstanceState
更改为以下内容:
@Override
public void onSaveInstanceState (Bundle outState) {
this.initialScrollPosition = this.getListView().getFirstVisiblePosition();
View firstVisibleItemView = this.getListView().getChildAt(0);
this.initialScrollYOffset = (firstVisibleItemView == null) ? 0 : firstVisibleItemView.getTop();
outState.putInt(SCROLL_POSITION, this.initialScrollPosition);
outState.putInt(SCROLL_Y_OFFSET, this.initialScrollYOffset);
}