自定义View 实现多级树形结构显示

项目截图

 

 

实体类 MyNodeBean

public class MyNodeBean {
    private String ids;
    private String pIds;
    /**
     * 节点Id
     */
    private int id;
    /**
     * 节点父id
     */
    private int pId;
    /**
     * 节点name
     */
    private String name;
    /**
     *
     */
    private String desc;
    /**
     * 节点名字长度
     */
    private long length;




    public MyNodeBean(int id, int pId, String ids,String pIds,String name) {
        super();
        this.id = id;
        this.pId = pId;
        this.ids=ids;
        this.pIds=pIds;
        this.name = name;
    }


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getPid() {
        return pId;
    }
    public void setPid(int pId) {
        this.pId = pId;
    }


    public String getIds() {
        return ids;
    }


    public void setIds(String ids) {
        this.ids = ids;
    }


    public String getpIds() {
        return pIds;
    }


    public void setpIds(String pIds) {
        this.pIds = pIds;
    }


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public long getLength() {
        return length;
    }
    public void setLength(long length) {
        this.length = length;
    }


}

 

 

实体类 Node

public class Node {
    private String ids;
    private String pIds;
    /**
     * 节点id
     */
    private int id;
    /**
     * 父节点id
     */
    private int pId;
    /**
     * 是否展开
     */
    private boolean isExpand = false;
    private boolean isChecked = false;
    private boolean isHideChecked = true;
    /**
     * 节点名字
     */
    private String name;
    /**
     * 节点级别
     */
    private int level;
    /**
     * 节点展示图标
     */
    private int icon;
    /**
     * 节点所含的子节点
     */
    private List<Node> childrenNodes = new ArrayList<Node>();
    /**
     * 节点的父节点
     */
    private Node parent;


    public Node() {
    }


    public Node(int id, int pId, String ids,String pIds,String name) {
        super();
        this.id = id;
        this.pId = pId;
        this.ids=ids;
        this.pIds=pIds;
        this.name = name;
    }


    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }


    public int getpId() {
        return pId;
    }


    public void setpId(int pId) {
        this.pId = pId;
    }


    public String getIds() {
        return ids;
    }


    public void setIds(String ids) {
        this.ids = ids;
    }


    public String getpIds() {
        return pIds;
    }


    public void setpIds(String pIds) {
        this.pIds = pIds;
    }


    public boolean isExpand() {
        return isExpand;
    }


    /**
     * 当父节点收起,其子节点也收起
     * @param isExpand
     */
    public void setExpand(boolean isExpand) {
        this.isExpand = isExpand;
        if (!isExpand) {


            for (Node node : childrenNodes) {
                node.setExpand(isExpand);
            }
        }
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public int getLevel() {
        return parent == null ? 0 : parent.getLevel() + 1;
    }


    public void setLevel(int level) {
        this.level = level;
    }


    public int getIcon() {
        return icon;
    }


    public void setIcon(int icon) {
        this.icon = icon;
    }


    public List<Node> getChildrenNodes() {
        return childrenNodes;
    }


    public void setChildrenNodes(List<Node> childrenNodes) {
        this.childrenNodes = childrenNodes;
    }


    public Node getParent() {
        return parent;
    }


    public void setParent(Node parent) {
        this.parent = parent;
    }


    /**
     * 判断是否是根节点
     *
     * @return
     */
    public boolean isRoot() {
        return parent == null;
    }


    /**
     * 判断是否是叶子节点
     *
     * @return
     */
    public boolean isLeaf() {
        return childrenNodes.size() == 0;
    }




    /**
     * 判断父节点是否展开
     *
     * @return
     */
    public boolean isParentExpand()
    {
        if (parent == null)
            return false;
        return parent.isExpand();
    }


    public boolean isChecked() {
        return isChecked;
    }


    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }


    public boolean isHideChecked() {
        return isHideChecked;
    }


    public void setHideChecked(boolean isHideChecked) {
        this.isHideChecked = isHideChecked;
    }

}

 

 

适配器 TreeListViewAdapter

public abstract class TreeListViewAdapter<T> extends BaseAdapter {


    protected Context mContext;
    /**
     * 存储所有可见的Node
     */
    protected List<Node> mNodes;
    protected LayoutInflater mInflater;
    /**
     * 存储所有的Node
     */
    protected List<Node> mAllNodes;


    /**
     * 点击的回调接口
     */
    private OnTreeNodeClickListener onTreeNodeClickListener;


    public interface OnTreeNodeClickListener {
        /**
         * 处理node click事件
         * @param node
         * @param position
         */
        void onClick(Node node, int position);
        /**
         * 处理checkbox选择改变事件
         * @param node
         * @param position
         * @param checkedNodes
         */
        void onCheckChange(Node node, int position,List<Node> checkedNodes);
    }


    public void setOnTreeNodeClickListener(
            OnTreeNodeClickListener onTreeNodeClickListener) {
        this.onTreeNodeClickListener = onTreeNodeClickListener;
    }


    /**
     *
     * @param mTree
     * @param context
     * @param datas
     * @param defaultExpandLevel
     *            默认展开几级树
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public TreeListViewAdapter(ListView mTree, Context context, List<T> datas,
                               int defaultExpandLevel, boolean isHide)
            throws IllegalArgumentException, IllegalAccessException {
        mContext = context;
        /**
         * 对所有的Node进行排序
         */
        mAllNodes = TreeHelper
                .getSortedNodes(datas, defaultExpandLevel, isHide);
        /**
         * 过滤出可见的Node
         */
        mNodes = TreeHelper.filterVisibleNode(mAllNodes);
        mInflater = LayoutInflater.from(context);


        /**
         * 设置节点点击时,可以展开以及关闭;并且将ItemClick事件继续往外公布
         */
        mTree.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                expandOrCollapse(position);


                if (onTreeNodeClickListener != null) {
                    onTreeNodeClickListener.onClick(mNodes.get(position),
                            position);
                }
            }


        });


    }


    /**
     * 相应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();// 刷新视图
            }
        }
    }


    @Override
    public int getCount() {
        return mNodes.size();
    }


    @Override
    public Object getItem(int position) {
        return mNodes.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Node node = mNodes.get(position);


        convertView = getConvertView(node, position, convertView, parent);
        // 设置内边距
        convertView.setPadding(node.getLevel() * 30, 3, 3, 3);
        if (!node.isHideChecked()) {
            //获取各个节点所在的父布局
            RelativeLayout myView = (RelativeLayout) convertView;
            //父布局下的CheckBox
            CheckBox cb = (CheckBox) myView.getChildAt(1);
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){


                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                             boolean isChecked) {
                    TreeHelper.setNodeChecked(node, isChecked);
                    List<Node> checkedNodes = new ArrayList<Node>();
                    for(Node n:mAllNodes){
                        if(n.isChecked()){
                            checkedNodes.add(n);
                        }
                    }


                    onTreeNodeClickListener.onCheckChange(node,position,checkedNodes);
                    TreeListViewAdapter.this.notifyDataSetChanged();
                }


            });
        }


        return convertView;
    }


    public abstract View getConvertView(Node node, int position, View convertView, ViewGroup parent);


    /**
     * 更新
     * @param isHide
     */
    public void updateView(boolean isHide){
        for(Node node:mAllNodes){
            node.setHideChecked(isHide);
        }


        this.notifyDataSetChanged();
    }



}

 

 

 

适配器 MyTreeListViewAdapter

public class MyTreeListViewAdapter<T> extends TreeListViewAdapter<T> {


    public MyTreeListViewAdapter(ListView mTree, Context context, List<T> datas, int defaultExpandLevel, boolean isHide) throws IllegalArgumentException, IllegalAccessException {
        super(mTree, context, datas, defaultExpandLevel, isHide);
    }


    @Override
    public View getConvertView(Node node, int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.icon = (ImageView) convertView.findViewById(R.id.id_treenode_icon);
            viewHolder.label = (TextView) convertView.findViewById(R.id.id_treenode_name);
            viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.id_treeNode_check);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }


        if (node.getIcon() == -1) {
            viewHolder.icon.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.icon.setVisibility(View.VISIBLE);
            viewHolder.icon.setImageResource(node.getIcon());
        }


        if(node.isLeaf()){
            if (node.isHideChecked()) {
                viewHolder.checkBox.setVisibility(View.INVISIBLE);
            } else {
                viewHolder.checkBox.setVisibility(View.VISIBLE);
                setCheckBoxBg(viewHolder.checkBox, node.isChecked());
            }
        }else{//父节点不显示选择框
            viewHolder.checkBox.setVisibility(View.GONE);
        }
        viewHolder.label.setText(node.getName());
        return convertView;
    }


    /**
     * ViewHolder类
     * */


    private final class ViewHolder {
        private ImageView icon;
        private TextView label;
        private CheckBox checkBox;
    }


    /**
     * checkbox是否选中
     */


    private void setCheckBoxBg(CheckBox cb, boolean isChecked) {
        if (isChecked) {
            cb.setBackgroundResource(R.drawable.check_box_bg_check);
        } else {
            cb.setBackgroundResource(R.drawable.check_box_bg);
        }
    }



}

 

 

帮助类 TreeHelper

public class TreeHelper {


    /**
     * 根据所有节点获取可见节点
     *
     * @param allNodes
     * @return
     */


    public static List<Node> filterVisibleNode(List<Node> allNodes) {
        List<Node> visibleNodes = new ArrayList<Node>();
        for (Node node : allNodes) {
            // 如果为根节点,或者上层目录为展开状态
            if (node.isRoot() || node.isParentExpand()) {
                setNodeIcon(node);
                visibleNodes.add(node);
            }
        }
        return visibleNodes;
    }


    /**
     * 获取排序的所有节点
     *
     * @param datas
     * @param defaultExpandLevel
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */


    public static <T> List<Node> getSortedNodes(List<T> datas, int defaultExpandLevel, boolean isHide) throws IllegalAccessException, IllegalArgumentException {
        List<Node> sortedNodes = new ArrayList<Node>();
        // 将用户数据转化为List<Node>
        List<Node> nodes = convertData2Nodes(datas, isHide);
        // 拿到根节点
        List<Node> rootNodes = getRootNodes(nodes);
        // 排序以及设置Node间关系
        for (Node node : rootNodes) {
            addNode(sortedNodes, node, defaultExpandLevel, 1);
        }
        return sortedNodes;
    }


    /**
     * 把一个节点上的所有的内容都挂上去
     */


    private static void addNode(List<Node> nodes, Node node, int defaultExpandLeval, int currentLevel) {
        nodes.add(node);
        if (defaultExpandLeval >= currentLevel) {
            node.setExpand(true);
        }


        if (node.isLeaf())
            return;
        for (int i = 0; i < node.getChildrenNodes().size(); i++) {
            addNode(nodes, node.getChildrenNodes().get(i), defaultExpandLeval, currentLevel + 1);
        }
    }


    /**
     * 获取所有的根节点
     *
     * @param nodes
     * @return
     */
    public static List<Node> getRootNodes(List<Node> nodes) {
        List<Node> rootNodes = new ArrayList<Node>();
        for (Node node : nodes) {
            if (node.isRoot()) {
                rootNodes.add(node);
            }
        }


        return rootNodes;
    }


    /**
     * 将泛型datas转换为node
     *
     * @param datas
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static <T> List<Node> convertData2Nodes(List<T> datas, boolean isHide)
            throws IllegalAccessException, IllegalArgumentException {
        List<Node> nodes = new ArrayList<Node>();
        Node node = null;


        for (T t : datas) {
            int id = -1;
            int pId = -1;
            String ids=null;
            String pids=null;
            String name = null;


            Class<? extends Object> clazz = t.getClass();
            Field[] declaredFields = clazz.getDeclaredFields();
            /**
             * 与MyNodeBean实体一一对应
             */
            for (Field f : declaredFields) {
                if ("id".equals(f.getName())) {
                    f.setAccessible(true);
                    id = f.getInt(t);
                }


                if ("pId".equals(f.getName())) {
                    f.setAccessible(true);
                    pId = f.getInt(t);
                }


                if ("ids".equals(f.getName())) {
                    f.setAccessible(true);
                    ids = (String) f.get(t);
                }


                if ("pIds".equals(f.getName())) {
                    f.setAccessible(true);
                    pids = (String) f.get(t);
                }


                if ("name".equals(f.getName())) {
                    f.setAccessible(true);
                    name = (String) f.get(t);
                }


                if ("desc".equals(f.getName())) {
                    continue;
                }


                if ("length".equals(f.getName())) {
                    continue;
                }


                if (id == -1 && pId == -1 && ids==null&& pids==null&&name == null) {
                    break;
                }
            }


            node = new Node(id, pId,ids,pids, name);
            node.setHideChecked(isHide);
            nodes.add(node);
        }


        /**
         * 比较nodes中的所有节点,分别添加children和parent
         */
        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);
                if (n.getId() == m.getpId()) {
                    n.getChildrenNodes().add(m);
                    m.setParent(n);
                } else if (n.getpId() == m.getId()) {
                    n.setParent(m);
                    m.getChildrenNodes().add(n);
                }
            }
        }


        for (Node n : nodes) {
            setNodeIcon(n);
        }
        return nodes;
    }


    /**
     * 设置打开,关闭icon
     *
     * @param node
     */
    public static void setNodeIcon(Node node) {
        if (node.getChildrenNodes().size() > 0 && node.isExpand()) {
            node.setIcon(R.drawable.tree_expand);
        } else if (node.getChildrenNodes().size() > 0 && !node.isExpand()) {
            node.setIcon(R.drawable.tree_econpand);
        } else
            node.setIcon(-1);
    }


    public static void setNodeChecked(Node node, boolean isChecked) {
        // 自己设置是否选择
        node.setChecked(isChecked);
        /**
         * 非叶子节点,子节点处理
         */
        setChildrenNodeChecked(node, isChecked);
        /** 父节点处理 */
        setParentNodeChecked(node);


    }


    /**
     * 非叶子节点,子节点处理
     */
    private static void setChildrenNodeChecked(Node node, boolean isChecked) {
        node.setChecked(isChecked);
        if (!node.isLeaf()) {
            for (Node n : node.getChildrenNodes()) {
                // 所有子节点设置是否选择
                setChildrenNodeChecked(n, isChecked);
            }
        }
    }


    /**
     * 设置父节点选择
     *
     * @param node
     */
    private static void setParentNodeChecked(Node node) {


        /** 非根节点 */
        if (!node.isRoot()) {
            Node rootNode = node.getParent();
            boolean isAllChecked = true;
            for (Node n : rootNode.getChildrenNodes()) {
                if (!n.isChecked()) {
                    isAllChecked = false;
                    break;
                }
            }


            if (isAllChecked) {
                rootNode.setChecked(true);
            } else {
                rootNode.setChecked(false);
            }
            setParentNodeChecked(rootNode);
        }
    }



}

 

activity_treeview

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <include layout="@layout/apptoplayout_withtextview" />


    <RelativeLayout
        android:id="@+id/activity_treeview_sellayout"
        android:layout_width="match_parent"
        android:visibility="gone"
        android:layout_height="wrap_content">


        <TextView
            android:id="@+id/activity_treeview_seltextview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:gravity="center|left"
            android:lineSpacingExtra="5dp"
            android:text="已选择:备件或人工设备备件或人工设备"
            android:textColor="@color/textviewcolor_333333"
            android:textSize="14sp"
            android:visibility="visible" />


        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@+id/activity_treeview_seltextview"
            android:layout_marginTop="10dp"
            android:background="@color/appline_color" />
    </RelativeLayout>




    <ListView
        android:id="@+id/activity_treeview_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@color/appline_color"
        android:dividerHeight="0.5dp"
        android:scrollbars="none"
        android:visibility="visible" />


    <TextView
        android:id="@+id/activity_treeview_textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="@color/textviewcolor_696969"
        android:textSize="14sp"
        android:visibility="gone" />
</LinearLayout>

 

list_item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp">


    <ImageView
        android:id="@+id/id_treenode_icon"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentLeft="true"
        android:layout_centerInParent="true"
        android:layout_marginLeft="10dp"
        android:scaleType="fitCenter"
        android:src="@drawable/tree_econpand" />


    <CheckBox
        android:id="@+id/id_treeNode_check"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerInParent="true"
        android:layout_marginLeft="10dp"
        android:visibility="visible"
        android:layout_toRightOf="@id/id_treenode_icon"
        android:background="@drawable/check_box_bg"
        android:button="@null"
        android:focusable="false" />


    <TextView
        android:id="@+id/id_treenode_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/id_treeNode_check"
        android:text="备件或人工设备备件或人工设备备件或人工设备备件或人工设备备件或人工设备备件或人工设备"
        android:singleLine="true"
        android:ellipsize="end"
        android:textColor="@color/textviewcolor_696969"
        android:textSize="14sp" />



</RelativeLayout>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值