如何保持ExpandableListView的展开状态?

18

我在我的

ExpandableListActivity

中使用了

SimpleExpandableListAdapter

当用户单击组行时,子列表会展开并显示,当用户单击扩展列表中的每个子项时,用户将被导航到下一个second_Activity。目前,当用户从second_Activity点击返回按钮返回到ExpandableListActivity时,可扩展列表将初始化为未展开状态,我希望可扩展列表保持展开状态,以便用户知道之前选择了哪个项目。如何实现这一点?应该覆盖ExpandableListActivity中的哪个方法?

PS:我知道我应该把getExpandableListView().expandGroup(groupPosition);放在某个地方,但是在哪里呢?我尝试将此代码放在onGroupClick()onChildClick()中,但没有帮助。

6个回答

65

对于一直展开的组,我扩展了SimpleExpandableListAdapter并在getGroupView方法中设置组为已展开:

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    View v = super.getGroupView(groupPosition, isExpanded, convertView, parent);
    ExpandableListView eLV = (ExpandableListView) parent;
    eLV.expandGroup(groupPosition);
    return v;
}

用这种方式做似乎有一些问题。显然(虽然我没有检查)ListView在滚动后失去焦点。但在我的情况下,它偶尔会在ExpandableListView.getFlatListPosition()期间导致随机的NullPointerException,当获取组的第一个子项时。在设置适配器后手动展开每个组似乎可以解决这个问题。 - technicalflaw
警告:如果您在空组中动态添加视图,则需要在getChildView中添加parent.expandGroup - cyrilchampier
没有遇到过这些问题,但是当你添加整个新组时,与每次更改时扩展所有内容相比,这更加简单。 - Warpzit

9

我在浏览中尝试寻找解决我的ExpandableListView问题的方法。无论如何,我想为adstro提供的答案添砖加瓦。

这个概念很简单: 首先调用ExpandableList适配器的getGroupCount()函数来找到组的数量, 然后循环遍历组并调用ExpandableList视图的expandGroup(int GroupPos)函数来展开每个组。

以上代码应该放在onCreate()和onResume()中,以便同时考虑第一次创建和之后返回活动的情况。


7
只在onResume中设置应该就足够了,因为任何经过onCreate的内容也会经过onResume。 - xaethos

3

adstro,你能发一下代码吗?我没能够完全理解它。 - ProgramME
2
@ProgramME 他的意思是 tmpListView.expandGroup(0);,考虑到您希望展开位置为0的组。如果您希望展开所有项目,请在for循环中执行。 - Jayshil Dave

2
 @Override
 View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup     parent) {
     View v = super.getGroupView(groupPosition, isExpanded, convertView, parent);
     ExpandableListView eLV = (ExpandableListView) parent;
     eLV.expandGroup(groupPosition);
     return v;
}

之后
     expListView.setOnChildClickListener(new OnChildClickListener() {

     @Override
     public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
         Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition)
             + " : " 
             + listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition),Toast.LENGTH_SHORT).show();
         return false;
     }
    });

onResume 中...

对我来说有效。滚动没有问题。


1

Straya提供的解决方案并不适用于Android 2.3.3。在列表滚动后,您的可扩展列表视图将失去焦点,并且单击事件将停止工作。


你对这种行为有什么解释吗?我以为那是个漏洞。 - glodos

0
我已经用这种方式完成了:
ExpandableAdpater adapter=new ExpandableAdapter(context);
expandableListView.setAdapter(adapter);

for (int i = 0; i < listResponse.size(); i++) {
                                expandableListView.expandGroup(i);
                            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接