Search code examples
androidexpandablelistviewexpandablelistadapter

Making ExpandableListView respect item margins and padding


I have an ExpandableListView that I'm populating with items. I'd like to have the header (here, "meat") be wider than the list items.

Main screen

However, ExpandableListView doesn't seem to respect margins/padding defined in XML, and also fails to respect programatically-set padding for the items. It does modify the parent ("meat") but the same code doesn't work for the items.

How can I do this?

Here's the relevant part of my custom adapter:

 @Override
 public View getGroupView(int position, boolean isExpanded, View view, ViewGroup parent) {
    if (view == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.list_category, null);
    }

    view.setPadding(10, 0, 10, 0); //RESPECTED

    initializeGroupComponents(view, getGroup(position));
    return view;
}

@Override
public View getChildView(int position, int expandedPosition, boolean isLastChild, View view, ViewGroup parent) {
    if (view == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.list_ingredient, parent, false);
    }

    view.setPadding(10, 2, 10, 2); //DOES NOT WORK

    initializeChildComponents(view, getChild(position, expandedPosition));
    return view;
}

The relevant portions of my XML:

The group:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_categoryContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="vertical">

The item:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/row"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_marginBottom="1dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="6dp"
android:background="@android:color/white"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">

Solution

  • Take one extra layout for header and add margin

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/layout_categoryContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <LinearLayout 
        android:layout_marginTop="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="5dp">
    
        //other content
        </LinearLayout>
        </LinearLayout>