Keep groups expanded in ExpandableListView

The title says it all, this post is about keeping all groups expanded in an ExpandableListView, even if the user tries to close it via touching a group header. To achieve this, use the code below in the onCreate() function in your activity or fragment subclass:

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

list.setOnGroupClickListener(new OnGroupClickListener() {

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        return true;
    }
});

The for statement opens all groups on start, the empty ongroupclick event ensures that the groups remain open even on a click event.

The former version of this post contained an other way, expanding the groups in the getGroupView() method of the BaseExpandableAdapter subclass. This was flawed in two ways, as jacob.yang and einzelkind pointed out in the comments (thanks for the feedback by the way).

  • The listview can lose focus after scrolling in Android 2.3.3.
  • It seems to randomly cause getFlatListPosition to occasionally cause a NullPointerException.
4 comments
  1. nice post . however the first solution have a bug for android version 2.3.3 . listview will lost focus after scrolling

    • andras k said:

      Thanks for pointing that out, I’ve modified the post.

  2. einzelkind said:

    In addition to the previous commenter’s warning, if you use the first version then it seems to randomly cause getFlatListPosition to occasionally cause a NullPointerException. I suspect it might be some sort of race condition when its internal structures are initialized. Manually expanding each group, ala the second solution, works ok.

    • andras k said:

      Thanks for the feedback, I’ve updated the post accordingly.

Leave a comment