使用RecyclerView实现无限层级可勾选的折叠树形TreeView
本文主要通过RecyclerView实现一个TreeView效果的控件,该控件使用简单,并且支持任意拓展到无限层级。
首先,需要先让要显示的Item继承于BaseItem,BeseItem主要拥有树形控件的逻辑操作属性,像标志是否被折叠展开了,以及子树的节点容器等等。

示例程序中的Section仅仅只是继承了BaseItem,有其提起啊业务需求的可以自己增加属性。

接下来我们就可以在Activity里面使用了。

接下来在最主要的就是对helper的初始化了,SectionExpandHelper的构造函数需要传入recyclerView,这里使用了包装设计模式,包装设计模式的使用场景就在系统提供的类的功能不能满足我们的需求的时候对其进行增强的一种方法。 然而,这不是我们关注的内容,我们只需传入这些参数即可使用。

IMultipleItem是一个回调接口,要实现这个层级树最主要的工作就是复写这个接口并复写对应的方。

我们再实现了IMultipleItem接口的匿名内部类里面定义三个变量记住不用层级的控件的layoutID,也就是说需要多少层级的控件就定义多少xml吗,这里我测试的时候只现实了三层级的控件,所有只定义了三个。
```
private static final intVIEW_TYPE_ITEM= R.layout.layout_item;
private static final intVIEW_TYPE_SECTION= R.layout.layout_section;
private static final intVIEW_TYPE_APK= R.layout.layout_apk;
```
在getItemLayout方法里面根据传过来的baseItem判断其具体实现并返回对应的layoutID

同理

bindData方法中使用的ViewHolder为万能适配器,只要将View的id传入就可以设置显示的文本图片等信息了。也可以通过view的id找到View。bindData中调用getItemLayout方法得到当前显示的item的视图id,然后对相应的视图进行操作。


最后就是显示效果了


到此为止就实现了折叠树的实现了,并实现了单选多选的功能。本人第一次写简书,写得不好还望大家见谅。。
网友评论