You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为含业务逻辑的ExpandableListView父项及子项添加边框?

我之前刚好做过类似的需求,分享下我的实现思路,应该能帮到你!

一、隐藏展开/折叠控件

这个很简单,有两种快速实现方式:

  • 直接在ExpandableListView的布局xml里添加属性:android:groupIndicator="@null",一步到位去掉默认的展开折叠指示器。
  • 如果你的适配器是自定义的,也可以在getGroupView()方法中,找到布局里的指示器控件(如果有的话)设置setVisibility(View.GONE),不过第一种方法更直接省心。

二、给父项和子项同时添加边框

默认属性确实没法直接实现这个效果,核心思路是给父项和子项分别使用带边框的自定义布局,完全不用动原有业务逻辑,只替换布局即可:

  1. 制作父项带边框的布局
    新建一个父项布局文件(比如item_expand_group.xml),根布局使用LinearLayout或RelativeLayout,然后给它设置一个带边框的drawable背景:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="12dp"
        android:background="@drawable/border_common">
    
        <!-- 这里放你原来父项的内容控件,比如TextView、ImageView等 -->
    
    </LinearLayout>
    

    然后在drawable目录下创建border_common.xml,定义边框样式:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="#fff" /> <!-- 背景色,根据你的皮肤调整 -->
        <stroke
            android:width="1dp"
            android:color="#e0e0e0" /> <!-- 边框颜色和宽度 -->
        <!-- 可选:添加圆角 -->
        <corners android:radius="4dp" />
    </shape>
    
  2. 制作子项带边框的布局
    同理新建子项布局文件(比如item_expand_child.xml),如果想要子项和父项衔接更自然(比如去掉子项顶部边框,避免和父项底部边框重叠),可以单独写一个子项的边框drawable:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="#fff" />
        <stroke
            android:width="1dp"
            android:color="#e0e0e0"
            android:topWidth="0dp" /> <!-- 去掉顶部边框 -->
        <corners android:radius="4dp" />
    </shape>
    

    然后把这个drawable设置为子项根布局的背景,再把原来子项的内容控件放进去就行。

  3. 适配到原有适配器
    找到你自定义的ExpandableListAdapter,在getGroupView()方法中加载父项的新布局,在getChildView()方法中加载子项的新布局就ok了——完全不用修改原有业务逻辑,只是替换了布局文件,对现有代码侵入极小。

另外提醒下:如果还需要保留父项的展开/折叠交互,隐藏指示器后点击父项依然能触发,这个功能不受影响哦。

内容的提问来源于stack exchange,提问作者Professor Chaos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:40:40