android expandablelist 自动滚动,android – 如何在ExpandableListView中保留滚动位置

经过几个实验,我来到了一个令人满意的解决方案,这也保留了顶部可见项目的细滚动位置.

事实上,需要保存和恢复三个不同的信息:列表状态(例如哪些组被展开),第一个可视项目的索引以及它的微滚动位置.

不幸的是,似乎只有第一个被可扩展列表视图的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设备上工作正常.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值