展开可扩展列表视图中的所有子项

77

我希望在可扩展列表视图(expandable list view)被填充时展开所有子项。 目前我的代码看起来像这样:

ExpandableListView listView = (ExpandableListView) findViewById(R.id.view);
int count = viewAdapted.getGroupCount();
for (int position = 1; position <= count; position++)
    listView.expandGroup(position - 1);

这种方式很丑陋。有没有更好的方法?


也许你可以看一下这个链接:https://dev59.com/l1nUa4cB1Zd3GeqPcqu_ - david55
目前看来这是唯一的解决方案。希望有一些属性或类似的东西。 - Drejc
当然 (position <= count) ... 复制粘贴错字 - Drejc
@Drejc:你能选出正确的答案吗? - Justin
有一个...但它已被删除。 - Drejc
当你说“它被删除了”是什么意思?你现在可以恢复它吗? - Justin
5个回答

79

你可以在自定义适配器的getGroupView方法中扩展它:

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

好运!


14
这会使它们无法被点击。 - David Lawson
2
@DavidLawson:是的,我的解决方案是固定扩展它们。如果你想要扩展它们并且它们是可点击的,你必须在创建ExpandableListView时处理它,就像Drejc的解决方案一样。 - Justin

39

将这段代码放在您的适配器上,将使可展开列表保持打开状态,并禁用其关闭功能。

ExpandableListView mExpandableListView = (ExpandableListView) parent;
mExpandableListView.expandGroup(groupPosition);

这可能是一个小技巧,但它的功能与预期相同。它在开始时打开所有组,并且可以随时关闭。

 for ( int i = 0; i < groupList.getCount(); i++ ) {
    groupList.expandGroup(i);
 } 

注意: 请在设置您的可扩展视图适配器后再放置此代码,否则可能会导致错误。希望它能帮到您。


无论您将此代码放在setAdapter之前还是之后,都没有关系。但是您应该在为适配器设置数据后再放置它。如果您先设置适配器,然后再通过网络加载数据,这就很有意义了。 - Anatolii Shuba

8

首先填充适配器,然后将此代码放入您的oncreate方法中。

   int count = adapter.getGroupCount();
                for ( int i = 0; i < count; i++ ) 
                    listView.expandGroup(i);

7

展开所有分组

for(int i=0; i < myAdapter.getGroupCount(); i++)
    myExpandableListView.expandGroup(i);

如果您希望使它们无法折叠。
myExpandableListView.setOnGroupClickListener(new OnGroupClickListener() {
  @Override
  public boolean onGroupClick(ExpandableListView parent, View v,int  groupPosition, long id) { 
    return true; 
  }
});

1
我尝试了列出的响应,但发现我可以使用 getGroupCount() 方法来获取组数。
使用此方法,我可以迭代并展开我的 ExpandableListView 的每个组。
for (int i = 0; i < myExpandableListView.getExpandableListAdapter().getGroupCount(); i++) {
      //Expand group
      myExpandableListView.expandGroup(i);
 }

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