ListView 在设备切换横竖屏时保存状态

 

比如listview在设备切换横竖屏时,仍然需要保证position,

activity - > onSaveInstanceState  - > restoreInstanceState

view  - > onSaveInstanceState  - > restoreInstanceState

// YourActivity.java
private static final String LIST_STATE = "listState";
private Parcelable mListState = null;

// Write list state to bundle
@Override
protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    mListState = getListView().onSaveInstanceState();
    state.putParcelable(LIST_STATE, mListState);
}

// Restore list state from bundle
@Override
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);
    mListState = state.getParcelable(LIST_STATE);
}


@Override
protected void onResume() {
    super.onResume();
    loadData(); // 确保数据重新加载,并在daapter中刷新
    // 在api call 的success 的回调中restoreState
    if (mListState != null) {
        myListView.onRestoreInstanceState(mListState);
        mListState = null;
    }
}
  

  

 

posted @ 2017-02-16 15:52  戴杭林  阅读(535)  评论(0编辑  收藏  举报