pixel
pixel

Reputation: 10557

ExpandableListView - show only children elements if each parent has only 1 child

I am using ExpandableListView to show parent-children relationship in Activity. That works fine but because in our case, parent and child information is similar, I would like to be able to hide parent information in cases where each parent has only 1 child.

For example, in screenshot below, my 3 product currently showing all have one child each. Because most of useful information is sufficient on parts (child) views, I would like to hide parents (product) view.

So, instead of showing it like this when each product has only 1 part: enter image description here

, I would like to show it like this (without parent view): enter image description here

Is that possible with ExpandableListView?

Upvotes: 0

Views: 966

Answers (2)

Claud
Claud

Reputation: 1075

This is a hacky way but you can check if the children count is 1 and then inflate an empty view for the GroupView.

I'm using a viewHolder pattern but an example that works for me looks something like this.

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

    if(convertView == null){
        viewHolder = new ViewHolder();

        if(getChildrenCount(groupPosition) == 1) {
            //INFLATE EMPTY VIEW
            convertView = LayoutInflater.from(context).inflate(R.layout.empty_view, parent, false);
        } else {
            //THE ACTUAL VIEW
            convertView = LayoutInflater.from(context).inflate(R.layout.actual_view, parent, false);
            viewHolder.displayName = (TextView) convertView.findViewById(R.id.displayName);
        }

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    if(getChildrenCount(groupPosition) != 1) {
        viewHolder.name.setText("Name");
        listView.expandGroup(groupPosition);
    }


    return convertView;
}

empty_view.xml looks like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="0dp"
              android:layout_height="0dp">

</LinearLayout>

Upvotes: 1

David Rauca
David Rauca

Reputation: 1583

In my opinion using a recycler view will be easier for what you want to do. Here is a good example: https://www.bignerdranch.com/blog/expand-a-recyclerview-in-four-steps/

Upvotes: 0

Related Questions