在我的应用程序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
)不会被调用,因此无法恢复状态。
因此我有两个问题:
- 我该怎么做才能在没有回调的
savedInstanceState
情况下恢复后?onXXXCreated
- 生命周期到底在做什么。我想了解,为什么我的方法失败了。
非常感谢您的任何见解!
解决方案:
感谢安德烈!我把我改成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);
}