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.
About these ads
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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 27 other followers

%d bloggers like this: