gpt4 book ai didi

android - 每次我从另一个 Activity 返回时,ExpandableListView 都会折叠所有组项目

转载 作者:行者123 更新时间:2023-11-29 00:40:00 25 4
gpt4 key购买 nike

我需要有人指导我找错。当我接到一个电话或去参加另一项 Activity 时,当我回来时所有的组都折叠了。系统尚未销毁 Activity ,因此我无法保存和恢复 onRestoreInstanceState 中的状态,因为从未调用该方法( Activity 仅暂停和停止,但未销毁)。

Activity 扩展了 ExpandableListActivity,我使用的适配器是 SimpleCursorTreeAdapter。

在哪些情况下展开列表会折叠?我快疯了,找不到解决方案。

提前致谢。

编辑:这是我的 Activity 的生命周期
当 Activivy 第一次启动时:
onCreate() -> onStart() -> onResume()
当我去其他 Activity 时:
onPause() -> onStop()
当我回来时:
onRestart -> onStart( ) -> onResume()

最佳答案

不幸的是,只要失去焦点,展开状态总是会重置,并且当它再次获得焦点时不会调用 onCreate(),而是调用 onStart()。所以我现在的解决方法是手动存储所有展开项目的 ID,然后在 onStart() 中再次展开它们。我实现了 ExpandableListActivity 的子类以重用该行为。

public class PersistentExpandableListActivity extends ExpandableListActivity {

private long[] expandedIds;

@Override
protected void onStart() {
super.onStart();
if (this.expandedIds != null) {
restoreExpandedState(expandedIds);
}
}

@Override
protected void onStop() {
super.onStop();
expandedIds = getExpandedIds();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
this.expandedIds = getExpandedIds();
outState.putLongArray("ExpandedIds", this.expandedIds);
}

@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
long[] expandedIds = state.getLongArray("ExpandedIds");
if (expandedIds != null) {
restoreExpandedState(expandedIds);
}
}

private long[] getExpandedIds() {
ExpandableListView list = getExpandableListView();
ExpandableListAdapter adapter = getExpandableListAdapter();
if (adapter != null) {
int length = adapter.getGroupCount();
ArrayList<Long> expandedIds = new ArrayList<Long>();
for(int i=0; i < length; i++) {
if(list.isGroupExpanded(i)) {
expandedIds.add(adapter.getGroupId(i));
}
}
return toLongArray(expandedIds);
} else {
return null;
}
}

private void restoreExpandedState(long[] expandedIds) {
this.expandedIds = expandedIds;
if (expandedIds != null) {
ExpandableListView list = getExpandableListView();
ExpandableListAdapter adapter = getExpandableListAdapter();
if (adapter != null) {
for (int i=0; i<adapter.getGroupCount(); i++) {
long id = adapter.getGroupId(i);
if (inArray(expandedIds, id)) list.expandGroup(i);
}
}
}
}

private static boolean inArray(long[] array, long element) {
for (long l : array) {
if (l == element) {
return true;
}
}
return false;
}

private static long[] toLongArray(List<Long> list) {
long[] ret = new long[list.size()];
int i = 0;
for (Long e : list)
ret[i++] = e.longValue();
return ret;
}
}

也许有人有更好的解决方案。

关于android - 每次我从另一个 Activity 返回时,ExpandableListView 都会折叠所有组项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10014707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com