具体的思路可以查看博客:https://blog.csdn.net/qq_42024734/article/details/101430006 实现的功能如下:
- 实现列表的无限深度
- 父级元素可以对子级元素实现折叠或展开
- 列表每一级子元素的个数不确定,且子元素可以拥有无限的深度
- 被选中的元素字体颜色需要改变,被选中的只能有一个,即单选
- 选中元素的信息要可以提取出来,方便使用
只能自己动手写了,起初考虑用ExpandableListView,因为有现成的折叠功能,但是在实际操作中嵌套发现第三级无论如何都展不开。然后就开始考虑使用ListView,但到底是使用嵌套还是将所有的数据不使用嵌套,而是通过判断数据是第几级来控制左边距以此来达到层次感,最后觉得这样操作起来难道太大、判断太多而作罢。最后采用的办法就是LinearLayout动态向其中添加子项,如果子项有下一级,就再添加一个LinearLayout,这样导致最外层的LinearLayout的页面示意结构图如下: 从上面的示意图中可以看出,公司C有下一级,所以插入了一个LinearLayout,公司B的所有下一级都放在这个LinearLayout中,当点击公司C这个区域时,就可以对LinearLayout进行操作操作从而实现下一级的显示和隐藏,而不用对下一级的每一个子元素判断,可以提高判断效率。当下一级的某个元素部门C-1也有下一级时再在部门C-1的下面添加LinearLayout,里面放的是部门C-1的所有子元素,以此类推,遇到有下一级的就把所有子元素用LinearLayout装进去。另外,除了实现树状结构的折叠外,还需要在页面上标识出当前选中的是哪一个,被选中的字体变为蓝色,这里用的是递归遍历判断每一个元素是否被选中。 另外,由于到底有多少级,每一级又有多少元素都是无法确定的,这里使用的是手动解析,通过判断是否有下一级来添加LinearLayout和子元素。解析时使用了递归。