ExpandableListView expand only on a specific Button?

mkl picture mkl · Jan 29, 2013 · Viewed 18.4k times · Source

well i´m trying to create a ExpandableListView like Spotify it does... But i don´t have any idea how do disable the LinearLayout to act like a button (Expand the list) I have created a image which should describe what i like. I like to have the possibility to handle a click on the text / image (parent) as a normal interaction. A click on the right button should expand the list like in Spotify...

First picture show the expand action (now), second show the expand action how it should be...

Answer

Dimmy3 picture Dimmy3 · Jul 18, 2014

This is a bit old question, but this answer might help someone.

If you want to expand/collapse group by clicking on specific Button or some other View, you have to get that Button in getGroupView method in your Adapter class. Then, in onClick method of your Button you have, either to cast parent to ExpandableListView, or to pass List's reference in constructor when you create adapter.

I prefer the first approach. Here's the code, assuming that you have one TextView and an ImageView that is the arrow. I've added changing the arrow state too.

@Override
public View getGroupView(final int groupPosition, final boolean isExpanded,
        View convertView, final ViewGroup parent) {

    String headerTitle = (String) getGroup(groupPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.left_drawer_list_group, parent, false);
    }

    TextView listHeaderText = (TextView) convertView
            .findViewById(R.id.left_menu_list_header_text);
    ImageView listHeaderArrow = (ImageView) convertView.findViewById(R.id.left_menu_list_header_arrow);

    listHeaderText.setText(headerTitle);

    //Set the arrow programatically, so we can control it
    int imageResourceId = isExpanded ? android.R.drawable.arrow_up_float : android.R.drawable.arrow_down_float;
    listHeaderArrow.setImageResource(imageResourceId);

    listHeaderArrow.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if(isExpanded) ((ExpandableListView) parent).collapseGroup(groupPosition);
            else ((ExpandableListView) parent).expandGroup(groupPosition, true);

        }
    });

    return convertView;
}

Additionally, you would like to disable expanding/collapsing in onGroupClick listener.

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

    //Do some other stuff, but you shall not expand or collapse

    return true;
}

There is another method, but the fairly bad one, and that is that you copy entire Adapter class inside the class where you create ExpandableListView and set Adapter. But do not do that. Seriously! ;)