Spires
Spires

Reputation: 35

Expandable list view - collapse an item on expanding another item (Android)

I have used expandable list view to implement dropdown functionality in my navigation drawer items. Right now, if I expand a navigation drawer item, and then expand another one - both item remains expanded. What I want is that when I expand an item, and then expand another one, the previous one collapses.

I have used the below code to try to do that:

expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
               
                        for (Map.Entry mapElement : expandabilityMap.entrySet()) {
                            int groupPos = (int) mapElement.getKey();
                            boolean isExpanded = (boolean) mapElement.getValue();
                            if (isExpanded) {
                                parent.collapseGroup(groupPos);
                            }

                            expandabilityMap.put(groupPosition, true);
                        }
                return false;


            }

        });

I have a hashmap named 'expandabilityMap' in which I store the navigation drawer item position as key, and 'true' or 'false' as values - true if the item at that position is expanded, and false otherwise.

Above code is supposed to do the following things on clicking an item in navigation drawer:

  1. Get keys and values from hashmap.
  2. If there is 'true' value then collapse the item at the corresponding position.
  3. Put the currently clicked item position in hashmap along with 'true' value.
  4. Expand the clicked item.

But after running my app, when I expand an item, it expands. But when I try to expand another item, my app crashes.

I get the following exception:

E/MessageQueue-JNI: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0

I'm unable to fix this. Please help!

Upvotes: 1

Views: 1396

Answers (1)

i_A_mok
i_A_mok

Reputation: 2904

Try this:

    expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        int previousGroup = -1;
        @Override
        public void onGroupExpand(int groupPosition) {
            if (groupPosition != previousGroup)
                expandableListView.collapseGroup(previousGroup);
            previousGroup = groupPosition;
        }
    });

Upvotes: 2

Related Questions