【问题标题】:Making ExpandableListView respect item margins and padding使 ExpandableListView 尊重项目边距和填充
【发布时间】:2018-02-05 04:35:39
【问题描述】:

我有一个用项目填充的 ExpandableListView。我想让标题(这里是“肉”)比列表项更宽。

但是,ExpandableListView 似乎不遵守 XML 中定义的边距/填充,并且也不遵守以编程方式为项目设置的填充。它确实修改了父项(“肉”),但相同的代码不适用于项目。

我该怎么做?

这是我的自定义适配器的相关部分:

 @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;
}

我的 XML 的相关部分:

小组:

<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">

物品:

<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">

【问题讨论】:

    标签: android expandablelistview expandablelistadapter


    【解决方案1】:

    为页眉多取一个布局并添加边距

     <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>
    

    【讨论】:

    • 完美!谢谢!