经过几个实验,我来到了一个令人满意的解决方案,这也保留了顶部可见项目的细滚动位置.
事实上,需要保存和恢复三个不同的信息:列表状态(例如哪些组被展开),第一个可视项目的索引以及它的微滚动位置.
不幸的是,似乎只有第一个被可扩展列表视图的onSaveInstanceState方法保存,所以另外两个需要单独保存.这与不可扩展列表视图不同,在这里,似乎onSaveInstanceState方法可以保存正确恢复列表状态和位置所需的所有信息(关于此主题,请参阅Scroll to a position in a listView).
以下是代码段;在ExpandableListActivity派生类之上:
private static final String LIST_STATE_KEY = "listState";
private static final String LIST_POSITION_KEY = "listPosition";
private static final String ITEM_POSITION_KEY = "itemPosition";
private Parcelable mListState = null;
private int mListPosition = 0;
private int mItemPosition = 0;
然后,一些覆盖:
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
mListState = state.getParcelable(LIST_STATE_KEY);
mListPosition = state.getInt(LIST_POSITION_KEY);
mItemPosition = state.getInt(ITEM_POSITION_KEY);
}
protected void onResume() {
super.onResume();
// Load data from DB and put it onto the list
loadData();
// Restore list state and list/item positions
ExpandableListView listView = getExpandableListView();
if (mListState != null)
listView.onRestoreInstanceState(mListState);
listView.setSelectionFromTop(mListPosition, mItemPosition);
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
ExpandableListView listView = getExpandableListView();
mListState = listView.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
// Save position of first visible item
mListPosition = listView.getFirstVisiblePosition();
state.putInt(LIST_POSITION_KEY, mListPosition);
// Save scroll position of item
View itemView = listView.getChildAt(0);
mItemPosition = itemView == null ? 0 : itemView.getTop();
state.putInt(ITEM_POSITION_KEY, mItemPosition);
}
这在我的Froyo设备上工作正常.