本文实例为大家分享了android RecycleView实现多级树形列表的具体代码,供大家参考,具体内容如下
实现多级树状列表:
1. Node.java
public class Nodeimplements Serializable { /** * 传入的实体对象 */ public B bean; /** * 设置开启的图片 */ public int iconExpand = -1; /** * 设置关闭的图片 */ public int iconNoExpand = -1; private T id; /** * 根节点pId为0 */ private T pId; private String name; /** * 当前的级别 */ private int level; /** * 是否展开 */ private boolean isExpand = false; private int icon = -1; /** * 下一级的子Node */ private List children = new ArrayList<>(); /** * 父Node */ private Node parent; /** * 是否被checked选中 */ private boolean isChecked; /** * 是否为新添加的 */ public boolean isNewAdd = true; /** * 单选标记 */ public boolean isSingle; /** * 支部code */ public String braCode; public Node(T id, T pId, String name) { super(); this.id = id; this.pId = pId; this.name = name; } public Node(T id, T pId, String name, B bean) { super(); this.id = id; this.pId = pId; this.name = name; this.bean = bean; } public String getBraCode() { return braCode; } public void setBraCode(String braCode) { this.braCode = braCode; } public boolean isSingle() { return isSingle; } public void setSingle(boolean single) { isSingle = single; } public boolean isChecked() { return isChecked; } public void setChecked(boolean isChecked) { this.isChecked = isChecked; } public Node() { } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public T getId() { return id; } public void setId(T id) { this.id = id; } public T getpId() { return pId; } public void setpId(T pId) { this.pId = pId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setLevel(int level) { this.level = level; } public boolean isExpand() { return isExpand; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } /** * 是否为跟节点 * * @return */ public boolean isRoot() { return parent == null; } /** * 判断父节点是否展开 * * @return */ public boolean isParentExpand() { if (parent == null){ return false; } return parent.isExpand(); } /** * 是否是叶子界点 * * @return */ public boolean isLeaf() { return children.size() == 0; } /** * 获取level */ public int getLevel() { return parent == null ? 0 : parent.getLevel() + 1; } /** * 设置展开 * * @param isExpand */ public void setExpand(boolean isExpand) { this.isExpand = isExpand; if (!isExpand) { for (Node node : children) { node.setExpand(false); } } } }
2. OnTreeNodeClickListener.java
public interface OnTreeNodeClickListener { /** * 点击事件方法 * @param node 节点 * @param position 条目位置 */ void onClick(Node node, int position); }
3. TreeHelper.java
public class TreeHelper { /** * 传入node 返回排序后的Node * * @param datas 传入数据 * @param defaultExpandLevel 默认展开等级 * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static ListgetSortedNodes(List datas, int defaultExpandLevel) { List result = new ArrayList (); // 设置Node间父子关系 List nodes = convetData2Node(datas); // 拿到根节点 List rootNodes = getRootNodes(nodes); // 排序以及设置Node间关系 for (Node node : rootNodes) { addNode(result, node, defaultExpandLevel, 1); } return result; } /** * 过滤出所有可见的Node * * @param nodes * @return */ public static List filterVisibleNode(List nodes) { List result = new ArrayList (); for (Node node : nodes) { // 如果为跟节点,或者上层目录为展开状态 if (node.isRoot() || node.isParentExpand()) { setNodeIcon(node); result.add(node); } } return result; } /** * 设置Node间,父子关系;让每两个节点都比较一次,即可设置其中的关系 */ private static List convetData2Node(List nodes) { for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); for (int j = i + 1; j < nodes.size(); j++) { Node m = nodes.get(j); //判断id是String,Integer if (m.getpId() instanceof String) { if (m.getpId().equals(n.getId())) { n.getChildren().add(m); m.setParent(n); } else if (m.getId().equals(n.getpId())) { m.getChildren().add(n); n.setParent(m); } } else if(m.getpId() instanceof Integer) { //这里就是修改的地方,因为这是Integer类,节点的地址是不一样的,所以不能直接使用==比较,要用equals()进行值的比较 if (m.getpId().equals(n.getId())) { n.getChildren().add(m); m.setParent(n); } else if (m.getId().equals(n.getpId())) { m.getChildren().add(n); n.setParent(m); } } } } return nodes; } /** * 获取所有根节点 * * @param nodes * @return */ private static List getRootNodes(List nodes) { List root = new ArrayList (); for (Node node : nodes) { if (node.isRoot()) { root.add(node); } } return root; } /** * 把一个节点上的所有的内容都挂上去 */ private static void addNode(List nodes, Node node, int defaultExpandLeval, int currentLevel) { nodes.add(node); //判断添加新节点的时候,保持以前的状态不变 if (node.isNewAdd && defaultExpandLeval >= currentLevel) { node.setExpand(true); } if (node.isLeaf()) { //判断是子节点 return; } for (int i = 0; i < node.getChildren().size(); i++) { addNode(nodes, node.getChildren().get(i), defaultExpandLeval, currentLevel + 1); } } /** * 设置节点的图标 * * @param node */ private static void setNodeIcon(Node node) { if (node.getChildren().size() > 0 && node.isExpand()) { node.setIcon(node.iconExpand); } else if (node.getChildren().size() > 0 && !node.isExpand()) { node.setIcon(node.iconNoExpand); } else { node.setIcon(-1); } } }
4. TreeRecyclerAdapter.java -----RecycleView形式的树形列表适配器
public abstract class TreeRecyclerAdapter extends RecyclerView.Adapter{ protected Context mContext; /** * 存储所有可见的Node */ protected List mNodes = new ArrayList<>(); protected LayoutInflater mInflater; /** * 存储所有的Node */ protected List mAllNodes = new ArrayList<>(); /** * 点击的回调接口 */ private OnTreeNodeClickListener onTreeNodeClickListener; /** * 默认不展开 */ private int defaultExpandLevel = 0; /** * 展开与关闭的图片 */ private int iconExpand = -1, iconNoExpand = -1; /** * 当前被点击的位置 */ private int layoutPosition = -1; public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTreeNodeClickListener) { this.onTreeNodeClickListener = onTreeNodeClickListener; } public TreeRecyclerAdapter(RecyclerView mTree, Context context, List datas, int defaultExpandLevel, int iconExpand, int iconNoExpand) { this.iconExpand = iconExpand; this.iconNoExpand = iconNoExpand; for (Node node : datas) { node.getChildren().clear(); node.iconExpand = iconExpand; node.iconNoExpand = iconNoExpand; } this.defaultExpandLevel = defaultExpandLevel; mContext = context; /** * 对所有的Node进行排序 */ mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel); /** * 过滤出可见的Node */ mNodes = TreeHelper.filterVisibleNode(mAllNodes); mInflater = LayoutInflater.from(context); } /** * @param mTree * @param context * @param datas * @param defaultExpandLevel 默认展开几级树 */ public TreeRecyclerAdapter(RecyclerView mTree, Context context, List datas, int defaultExpandLevel) { this(mTree, context, datas, defaultExpandLevel, -1, -1); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { Node node = mNodes.get(position); // convertView = getConvertView(node, position, convertView, parent); // 设置内边距 int padding = DisplayUtil.dp2px(mContext,5); holder.itemView.setPadding(DisplayUtil.dp2px(mContext,(node.getLevel()+1) * 15), padding,padding,padding); //然后设置单选,修改如下 /** * 设置节点点击时,可以展开以及关闭,将事件继续往外公布 */ holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取当前点击的位置 layoutPosition = holder.getLayoutPosition(); expandOrCollapse(position); if (onTreeNodeClickListener != null) { onTreeNodeClickListener.onClick(mNodes.get(position), position); } } }); if(position == layoutPosition){ node.setSingle(true); }else { node.setSingle(false); } onBindViewHolder(node, holder, position); } @Override public int getItemCount() { return mNodes.size(); } /** * 清除掉之前数据并刷新 重新添加 * * @param mlists * @param defaultExpandLevel 默认展开几级列表 */ public void addDataAll(List mlists, int defaultExpandLevel) { mAllNodes.clear(); addData(-1, mlists, defaultExpandLevel); } /** * 在指定位置添加数据并刷新 可指定刷新后显示层级 * * @param index * @param mlists * @param defaultExpandLevel 默认展开几级列表 */ public void addData(int index, List mlists, int defaultExpandLevel) { this.defaultExpandLevel = defaultExpandLevel; notifyData(index, mlists); } /** * 在指定位置添加数据并刷新 * * @param index * @param mlists */ public void addData(int index, List mlists) { notifyData(index, mlists); } /** * 添加数据并刷新 * * @param mlists */ public void addData(List mlists) { addData(mlists, defaultExpandLevel); } /** * 添加数据并刷新 可指定刷新后显示层级 * * @param mlists * @param defaultExpandLevel */ public void addData(List mlists, int defaultExpandLevel) { this.defaultExpandLevel = defaultExpandLevel; notifyData(-1, mlists); } /** * 添加数据并刷新 * * @param node */ public void addData(Node node) { addData(node, defaultExpandLevel); } /** * 添加数据并刷新 可指定刷新后显示层级 * * @param node * @param defaultExpandLevel */ public void addData(Node node, int defaultExpandLevel) { List nodes = new ArrayList<>(); nodes.add(node); this.defaultExpandLevel = defaultExpandLevel; notifyData(-1, nodes); } /** * 刷新数据 * * @param index * @param mListNodes */ private void notifyData(int index, List mListNodes) { for (int i = 0; i < mListNodes.size(); i++) { Node node = mListNodes.get(i); node.getChildren().clear(); node.iconExpand = iconExpand; node.iconNoExpand = iconNoExpand; } for (int i = 0; i < mAllNodes.size(); i++) { Node node = mAllNodes.get(i); node.getChildren().clear(); node.isNewAdd = false; } if (index != -1) { mAllNodes.addAll(index, mListNodes); } else { mAllNodes.addAll(mListNodes); } /** * 对所有的Node进行排序 */ mAllNodes = TreeHelper.getSortedNodes(mAllNodes, defaultExpandLevel); /** * 过滤出可见的Node */ mNodes = TreeHelper.filterVisibleNode(mAllNodes); //刷新数据 notifyDataSetChanged(); } /** * 获取排序后所有节点 * * @return */ public List getAllNodes() { if (mAllNodes == null){ mAllNodes = new ArrayList (); } return mAllNodes; } /** * 相应ListView的点击事件 展开或关闭某节点 * * @param position */ public void expandOrCollapse(int position) { Node n = mNodes.get(position); if (n != null) { // 排除传入参数错误异常 if (!n.isLeaf()) { n.setExpand(!n.isExpand()); mNodes = TreeHelper.filterVisibleNode(mAllNodes); notifyDataSetChanged();// 刷新视图 } } } /** * 设置多选 * * @param node * @param checked */ protected void setChecked(final Node node, boolean checked) { node.setChecked(checked); setChildChecked(node, checked); if (node.getParent() != null){ setNodeParentChecked(node.getParent(), checked); } notifyDataSetChanged(); } /** * 设置是否选中 * * @param node * @param checked */ public void setChildChecked(Node node, boolean checked) { if (!node.isLeaf()) { node.setChecked(checked); for (Node childrenNode : node.getChildren()) { setChildChecked(childrenNode, checked); } } else { node.setChecked(checked); } } private void setNodeParentChecked(Node node, boolean checked) { if (checked) { node.setChecked(checked); if (node.getParent() != null){ setNodeParentChecked(node.getParent(), checked); } } else { List childrens = node.getChildren(); boolean isChecked = false; for (Node children : childrens) { if (children.isChecked()) { isChecked = true; } } //如果所有自节点都没有被选中 父节点也不选中 if (!isChecked) { node.setChecked(checked); } if (node.getParent() != null){ setNodeParentChecked(node.getParent(), checked); } } } public abstract void onBindViewHolder(Node node, RecyclerView.ViewHolder holder, final int position); //===================在这里添加修改选中位置的方法===================== /** * 设置选中位置 * @param selectedPosition */ public void setSelectedPosition(int selectedPosition) { this.layoutPosition = selectedPosition; } }
5. 自定义样式:
TypeTreeRecyclerAdapter.java
public class TypeTreeRecyclerAdapter extends TreeRecyclerAdapter { private static final String TAG = "TypeTreeRecyclerAdapter"; private boolean isSingle; public TypeTreeRecyclerAdapter(RecyclerView mTree, Context context, Listdatas, int defaultExpandLevel, int iconExpand, int iconNoExpand,boolean isSingle) { super(mTree, context, datas, defaultExpandLevel, iconExpand, iconNoExpand); this.isSingle = isSingle; } public TypeTreeRecyclerAdapter(RecyclerView mTree, Context context, List datas, int defaultExpandLevel) { super(mTree, context, datas, defaultExpandLevel); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MyHoder(View.inflate(mContext, R.layout.tree_list_item,null)); } @Override public void onBindViewHolder(final Node node, RecyclerView.ViewHolder holder, int position) { final MyHoder viewHolder = (MyHoder) holder; //todo do something viewHolder.cb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // setChecked(node,viewHolder.cb.isChecked()); setChildChecked(node,viewHolder.cb.isChecked()); listener.onItemClick(position); } }); viewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (isSingle) { if (b) { //如果checkbox的状态是选中的,那么除了被选中的那条数据,其他Node节点的checkbox状态都为false for (int i = 0; i < mAllNodes.size(); i++) { if (((Node) mAllNodes.get(i)).getId().equals(node.getId())) { Log.e(TAG,"note="+mAllNodes.get(i).getName()); ((Node) mAllNodes.get(i)).setChecked(b); } else { // Log.e(TAG,"1111 note="+mAllNodes.get(i).getName()); ((Node) mAllNodes.get(i)).setChecked(false); } } } else {//如果checkbox的状态是选中的,所有Node节点checkbox状态都为false for (int i = 0; i < mAllNodes.size(); i++) { if (((Node) mAllNodes.get(i)).getId().equals(node.getId())) { ((Node) mAllNodes.get(i)).setChecked(b); } } } } else { 如果checkbox是多选的,对应node节点的checkbox状态视用户的操作而定 for (int i = 0; i < mAllNodes.size(); i++) { if (((Node) mAllNodes.get(i)).getId().equals(node.getId())) ((Node) mAllNodes.get(i)).setChecked(b); } } } }); if (node.isChecked()){ viewHolder.cb.setChecked(true); }else { viewHolder.cb.setChecked(false); } if (node.getIcon() == -1) { viewHolder.icon.setVisibility(View.INVISIBLE); } else { viewHolder.icon.setVisibility(View.VISIBLE); viewHolder.icon.setImageResource(node.getIcon()); } viewHolder.label.setText(node.getName()); } public interface onAItemClickListener{ void onItemClick(int position); } private onAItemClickListener listener; public void setOnItemClickListener (onAItemClickListener onItemClickListener) { listener = onItemClickListener; } class MyHoder extends RecyclerView.ViewHolder{ public CheckBox cb; public TextView label; public ImageView icon; public MyHoder(View itemView) { super(itemView); cb = (CheckBox) itemView.findViewById(R.id.cb_select_tree); label = (TextView) itemView.findViewById(R.id.id_treenode_label); icon = (ImageView) itemView.findViewById(R.id.icon); } } }
6. tree_list_item.xml
7. 页面:
public class OfficeTypeDialog extends Dialog implements View.OnClickListener { private static final String TAG = "OfficeTypeDialog"; private Context mContext; private RecyclerView rv_typeTree; private TypeTreeRecyclerAdapter typeTreeRecyclerAdapter; private TypeTreeBean selectedBean; private Button btn_confirm,btn_cancel; private String source; private String orgId; public OfficeTypeDialog(@NonNull Context context) { super(context); mContext = context; } public OfficeTypeDialog(@NonNull Context context, int themeResId) { super(context, themeResId); mContext = context; } public OfficeTypeDialog(@NonNull Context context, int themeResId,String source) { super(context, themeResId); mContext = context; this.source = source; } public OfficeTypeDialog(@NonNull Context context, int themeResId,String source,String orgId) { super(context, themeResId); mContext = context; this.source = source; this.orgId = orgId; } protected OfficeTypeDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); mContext = context; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_office_type); getWindow().setGravity(Gravity.CENTER); //显示在 WindowManager m = getWindow().getWindowManager(); Display d = m.getDefaultDisplay(); WindowManager.LayoutParams p = getWindow().getAttributes(); p.width = d.getWidth()/5*4; //设置dialog的宽度为当前手机屏幕的宽度 p.height = d.getHeight()/5*4; getWindow().setAttributes(p); rv_typeTree = findViewById(R.id.rv_typeTree); btn_confirm = findViewById(R.id.btn_confirm); btn_cancel = findViewById(R.id.btn_cancel); btn_confirm.setOnClickListener(this); btn_cancel.setOnClickListener(this); getOfficeType(); } ListmDatas = new ArrayList<>(); private List typeTreeBeans = new ArrayList<>(); private void getOfficeType() { String url = ""; if (source.equals("officeType")) { url = WebApi.OFFICE_TYPE; } else if(source.equals("area")) { url = WebApi.OFFICE_AREA; } else if(source.equals("nmpa")) { url = WebApi.OFFICE_NMPA; } else if(source.equals("nmpaUser")) { if (orgId != null) { url = WebApi.OFFICE_NMPA_USER+"?orgId="+orgId; } } OkHttpUtil.get(TAG, url, new StringCallback() { @Override public void onError(Call call, Exception e, int id) { Log.e(TAG,"getOfficeType e="+e); } @Override public void onResponse(String response, int id) { Log.e(TAG,"getOfficeType response="+response); try { JSONObject object = new JSONObject(response); if (object.getInt("code") == 200) { JSONArray array = object.getJSONArray("data"); Gson gson = new Gson(); for (int i = 0;i typeTreeBeans1 = typeTreeBean.getChildren(); for (int j1 = 0;j1 typeTreeBeans2 = typeTreeBean1.getChildren(); for (int j2 = 0;j2 typeTreeBeans3 = typeTreeBean2.getChildren(); for (int j3 = 0;j3 typeTreeBeans4 = typeTreeBean3.getChildren(); for (int j4 = 0;j4 typeTreeBeanList = new ArrayList<>(); final List allNodes = typeTreeRecyclerAdapter.getAllNodes(); for (int i = 0; i < allNodes.size(); i++) { if (allNodes.get(i).isChecked()){ // sb.append(allNodes.get(i).getName()+","); typeTreeBeanList.add((TypeTreeBean) allNodes.get(i).bean); } } // String strNodesName = sb.toString(); if (typeTreeBeanList != null && typeTreeBeanList.size() != 0) { Log.e(TAG,"bean="+typeTreeBeanList.get(0).getName()); selectedBean = typeTreeBeanList.get(0); } } /** * 设置确定取消按钮的回调 */ public OnClickBottomListener onClickBottomListener; public void setOnClickBottomListener(OnClickBottomListener onClickBottomListener) { this.onClickBottomListener = onClickBottomListener; } public interface OnClickBottomListener{ /** * 点击确定按钮事件 */ public void onPositiveClick(TypeTreeBean typeBean); /** * 点击取消按钮事件 */ public void onNegtiveClick(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_confirm: if ( onClickBottomListener!= null) { onClickBottomListener.onPositiveClick(selectedBean); } break; case R.id.btn_cancel: if ( onClickBottomListener!= null) { onClickBottomListener.onNegtiveClick(); } break; } } }
8. 调用dialog
OfficeTypeDialog typeDialog = new OfficeTypeDialog(mContext,R.style.Dialog,"officeType"); typeDialog.setOnClickBottomListener(new OfficeTypeDialog.OnClickBottomListener() { @Override public void onPositiveClick(TypeTreeBean typeBean) { tv_officeType.setText(typeBean.getName()); officeType = typeBean; typeDialog.dismiss(); } @Override public void onNegtiveClick() { typeDialog.dismiss(); } }); typeDialog.show();
9. 效果图
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。