2
在我的應用程序FragmentActivity
包含一個簡單的ListFragment
,我想保留用戶滾動到的位置。我做了以下內容:如何在恢復w/o savedInstanceState後恢復碎片狀態?
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
? - 這裏的生命週期究竟是什麼。我想了解,爲什麼我的方法失敗了。
非常感謝您的任何見解!
解決方案:
THX安德烈!我改變了我的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);
}