AI智能
改变未来

Android 树形结构数据的展示

这边建议使用

BaseRecyclerViewAdapterHelper

万能适配器在Recyclerview中显示

让你子对象和父对象分别继承

BaseNode和BaseExpandNode

这是BaseNode

abstract class BaseNode {/*** 重写此方法,获取子节点。如果没有子节点,返回 null 或者 空数组** 如果返回 null,则无法对子节点的数据进行新增和删除等操作*/abstract val childNode: MutableList<BaseNode>?}

这是BaseExpandNode

abstract class BaseExpandNode : BaseNode() {var isExpanded: Boolean = true}

继承之后父对象复写其中方法比如

public class FiveNode  extends BaseExpandNode {private List<BaseNode> childNode;private String title;private int id;private boolean hasChild;private String ip;private String type;public FiveNode(List<BaseNode> childNode, String title, int id,boolean hasChild,String ip,String type) {this.childNode = childNode;this.title = title;this.id = id;this.hasChild=hasChild;this.ip=ip;this.type=type;setExpanded(false);}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getTitle() {return title;}public int getId() {return id;}public boolean isHasChild(){return hasChild;}@Nullable@Overridepublic List<BaseNode> getChildNode() {return childNode;}}

适配器继承

BaseNodeAdapter
public class TreeAdapter extends BaseNodeAdapter {private onItemClickListener onItemClickListener;public TreeAdapter() {super();addNodeProvider(new FirstProvider());}@Overrideprotected int getItemType(@NotNull List<? extends BaseNode> list, int i) {BaseNode node = list.get(i);if (node instanceof FirstNode) {return 1;}return -1;}}

其中provider继承

BaseNodeProvider
public class FirstProvider extends BaseNodeProvider {@Overridepublic int getItemViewType() {return 1;}@Overridepublic int getLayoutId() {return R.layout.item_node_first;}@Overridepublic void convert(@NotNull BaseViewHolder baseViewHolder, @Nullable BaseNode baseNode) {}@Overridepublic void onClick(@NotNull BaseViewHolder helper, @NotNull View view, BaseNode data, int position) {getAdapter().expandOrCollapse(position);}}

效果图

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Android 树形结构数据的展示