前段时间项目的新功能里有些页面需要三层嵌套列表实现,虽然在移动端这种很丑,但是需求就是需求。
本来想用各种View嵌套,然后发现系统有个ExpandableListView。就直接拿来用了。
理论上来说,ExpandableListView的二级嵌套和三级嵌套没有本质区别,如果把二级嵌套的子级换成一个新的ExpandableListView,就可以实现三级嵌套。
有了思路,关于ExpandableListView的三层嵌套就直接上手实现
这里说下我的需求是有些数据是只有二级,有些数据是三级的。如果你的需求是只有三级,不需要考虑三级二级混合的情况,下面有说明怎么处理。
效果图
ExpandableListView
ExpandableListView是官方提供的一个可展示折叠列表的控件。官方文档直链
它的基本用法如下
基本用法
ExpandableListView的基本用法很简单,它本质上就是ListView,所以用法也差不多,这里就不介绍了。
如果有需要的,可以参考菜鸟教程ExpandableListView基本用法
下面开始进入正题。
布局文件
先说下,因为是三级嵌套,所以需要四个布局文件,Activity页面本身需要一个布局文件,然后就是三级嵌套的三个布局文件。
- Activity布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ExpandableListView
android:id="@+id/expand_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000"
android:childIndicator="@color/white"
android:divider="@null"
android:fadeScrollbars="false"
android:groupIndicator="@null"
android:listSelector="#00000000"
android:scrollbars="none" />
</LinearLayout>
我们可以通过ExpandableListView的默认属性来控制部分样式,这里贴上菜鸟教程的属性图片
- 一级菜单布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="44dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@drawable/chapter_gradient_group">
<TextView
android:id="@+id/adapter_title"
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginHorizontal=