Android 多级树形结构显示

1.项目截图



实体类1

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;
    }

}


实体2

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;
    }

}


适配器1

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();
    }


}

适配器2

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>


TreeViewActivity

public class TreeViewActivity extends BaseActivity implements View.OnClickListener,TreeListViewAdapter.OnTreeNodeClickListener{


    private RelativeLayout backlayout;
    private TextView titletextview;
    private TextView suretextview;
    private List<String> list;
    private List<String> showlist;
    private String result;
    private String showresult;
    private HashMap<String,Integer> idhashmap;
    private HashMap<String,Integer> pIdhashmap;
    private ToastUtils toast;
    private RelativeLayout sellayout;
    private TextView seltextview;
    private TextView nodatatextview;
    private ListView treeLv;
    private MyTreeListViewAdapter<MyNodeBean> adapter;
    private List<MyNodeBean> mDatas = new ArrayList<MyNodeBean>();
    private List<MyNodeBean> mDatass = new ArrayList<MyNodeBean>();
    private boolean isHide = false; //标记是显示Checkbox还是隐藏


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_treeview);
        initView();
    }


    /**
     * 初始化各种View
     * */


    private void initView(){
        list=new ArrayList<>();
        showlist=new ArrayList<>();
        toast=new ToastUtils(this);
        backlayout= (RelativeLayout) findViewById(R.id.apptoplayout_withtextview_backlayout);
        titletextview= (TextView) findViewById(R.id.apptoplayout_withtextview_titletextview);
        suretextview= (TextView) findViewById(R.id.apptoplayout_withtextview_righttextview);
        treeLv = (ListView) this.findViewById(R.id.activity_treeview_listview);
        nodatatextview= (TextView) findViewById(R.id.activity_treeview_textview);
        sellayout= (RelativeLayout) findViewById(R.id.activity_treeview_sellayout);
        seltextview= (TextView) findViewById(R.id.activity_treeview_seltextview);
        backlayout.setOnClickListener(this);
        suretextview.setOnClickListener(this);
        suretextview.setVisibility(View.INVISIBLE);
        sellayout.setVisibility(View.GONE);
        titletextview.setText(R.string.activity_treeviewtextview1);
        suretextview.setText(R.string.activity_treeviewtextview2);
        getSparePartsData();//获取备件数据
    }


    /**
     * 请求备件数据
     * */


    private void getSparePartsData(){
        //临时数据
        String context="[\n" +
//                "    \n" +
//                "    {\n" +
//                "        \"id\": \"002\",\n" +
//                "        \"pId\": \"001\",\n" +
//                "        \"name\": \"NUM2\"\n" +
//                "    },\n" +
//                "\t{\n" +
//                "        \"id\": \"003\",\n" +
//                "        \"pId\": \"002\",\n" +
//                "        \"name\": \"NUM3\"\n" +
//                "    },\n" +
//                "\t{\n" +
//                "        \"id\": \"004\",\n" +
//                "        \"pId\": \"003\",\n" +
//                "        \"name\": \"NUM4\"\n" +
//                "    },\n" +
//                "\t{\n" +
//                "        \"id\": \"005\",\n" +
//                "        \"pId\": \"004\",\n" +
//                "        \"name\": \"NUM5\"\n" +
//                "    },\n" +
//                "\t{\n" +
//                "        \"id\": \"001\",\n" +
//                "        \"pId\": \"100\",\n" +
//                "        \"name\": \"NUM1\"\n" +
//                "    }\n" +
//                "\t\n" +
//                "]";
        parseSparePartsData(context);
    }


    /**
     * Json解析备件数据
     * */


    private void parseSparePartsData(String context){
        try {
            JSONArray array=new JSONArray(context);
            int num=array.length();
            JSONObject object=null;
            MyNodeBean myNodeBean=null;
            idhashmap=new HashMap<>();
            pIdhashmap=new HashMap<>();
            for(int i=0;i<num;i++){
                object= (JSONObject) array.opt(i);
                String idstr=object.getString("id");
                String pidstr=object.getString("pId");
                String name=object.getString("name");
                myNodeBean=new MyNodeBean(0,0,idstr,pidstr,name);
                mDatass.add(myNodeBean);
                //将集合中的数据按pidstr倒序排序
                ComparatorTreeView comparatorTreeView=new ComparatorTreeView();
                Collections.sort(mDatass, comparatorTreeView);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        int nums=mDatass.size();
        if(nums>0){
            for(int i=0;i<nums;i++){
                MyNodeBean myNodeBean=mDatass.get(i);
                String idstr=myNodeBean.getIds();
                String pidstr=myNodeBean.getpIds();
                String name=myNodeBean.getName();


                /**
                 * 算法1
                 * */


                if(!BooleanUtils.isEmpty(idstr)&&!BooleanUtils.isEmpty(pidstr)){
                    //Id 在Pid集合中找
                    if(pIdhashmap.containsKey(idstr)){
                        Integer value=pIdhashmap.get(idstr);
                        idhashmap.put(idstr,value);
                    }else{
                        idhashmap.put(idstr,(i+1));
                    }
                    //Pid 在Id集合中找
                    if(idhashmap.containsKey(pidstr)){
                        Integer value=idhashmap.get(pidstr);
                        pIdhashmap.put(pidstr,value);
                    }else{
                        pIdhashmap.put(pidstr,(i+1));
                    }
                }


                int id=idhashmap.get(idstr);
                int pid=pIdhashmap.get(pidstr);


                /**
                 * 算法2
                 * */


//                int id=0;
//                int pid=0;
//                if(!(BooleanUtils.isEmpty(idstr))&&BooleanUtils.isNum(idstr)){
//                    id=Integer.parseInt(idstr);
//                }
//                if(!(BooleanUtils.isEmpty(pidstr))&&BooleanUtils.isNum(pidstr)){
//                    pid=Integer.parseInt(pidstr);
//                }


                myNodeBean=new MyNodeBean(id,pid,idstr,pidstr,name);
                mDatas.add(myNodeBean);
            }
        }


        if(mDatas.size()>0){//有数据
            treeLv.setVisibility(View.VISIBLE);
            nodatatextview.setVisibility(View.GONE);
            try {
                adapter = new MyTreeListViewAdapter<MyNodeBean>(treeLv, this, mDatas, 2, isHide);
                treeLv.setAdapter(adapter);
                adapter.setOnTreeNodeClickListener(this);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }else{//无数据
            treeLv.setVisibility(View.GONE);
            nodatatextview.setVisibility(View.VISIBLE);
            nodatatextview.setText(R.string.activity_treeviewtextview3);
        }


    }


    /**
     * TreeView点击
     * */


    @Override
    public void onClick(Node node, int position) {
        if (node.isLeaf()) {//叶子节点
            node.setHideChecked(false);//子节点始终不隐藏选择框
            String id=node.getIds();//NodeId
            String name=node.getName();//NodeName
            Node fathernode=node.getParent();//父Node
            String fathername="";
            if(null!=fathernode){//逐级获取父节点的NodeName
                boolean b=!fathernode.isLeaf();
                while (b){
                    fathername=fathernode.getName()+"-"+fathername;
                    fathernode=fathernode.getParent();
                    if(null!=fathernode){
                        b=!fathernode.isLeaf();
                    }else{
                        b=false;
                    }
                }
            }
            //获取点击的子节点结果(带id传给服务器)和子节点结果(不带id前台显示)
            result=fathername+name+","+id;
            showresult=fathername+name;
            //点击的子节点选中状态
            if(node.isChecked()){//选择框已选择 取消选择 并将结果删除
                node.setChecked(false);
                list.remove(result);
                showlist.remove(showresult);
            }else{//选择框未选择 选中 并将结果添加
                node.setChecked(true);
                list.add(result);
                showlist.add(showresult);
            }
            if(list.size()>0&&showlist.size()>0&&list.size()==showlist.size()){
                suretextview.setVisibility(View.VISIBLE);
                sellayout.setVisibility(View.VISIBLE);
                //显示结果
                int num=showlist.size();
                String result="";
                for(int i=0;i<num;i++){
                    result=result+showlist.get(i)+";";
                }
                seltextview.setText("已选择:"+result);
                //上传服务器
                int nums=list.size();
                String results="";
                for(int j=0;j<nums;j++){
                    results=results+list.get(j)+";";
                }
                toast.showToast(results);
            }else{
                suretextview.setVisibility(View.INVISIBLE);
                sellayout.setVisibility(View.GONE);
                seltextview.setText("");
            }
            adapter.notifyDataSetChanged();
        }
    }


    /**
     * TreeView选中
     * */


    @Override
    public void onCheckChange(Node node, int position, List<Node> checkedNodes) {
//        //首先以前选中的全部取消选中
//        int num=checkedNodes.size();
//        for(int i=0;i<num;i++){
//            Node nodes=checkedNodes.get(i);
//            nodes.setHideChecked(false);
//            nodes.setChecked(false);
//        }
//        //获取当前选中的节点
//        if (node.isLeaf()) {//叶子节点
//            node.setHideChecked(false);
//            node.setChecked(true);
//            String name=node.getName();
//            String id=String.valueOf(node.getId());
//            Node fathernode=node.getParent();
//            String fathername="";
//            if(null!=fathernode){
//                boolean b=!fathernode.isLeaf();
//                while (b){
//                    fathername=fathernode.getName()+"-"+fathername;
//                    fathernode=fathernode.getParent();
//                    if(null!=fathernode){
//                        b=!fathernode.isLeaf();
//                    }else{
//                        b=false;
//                    }
//                }
//            }
//            result=fathername+name+","+id;
//            showresult=fathername+name;
//            adapter.notifyDataSetChanged();
//            if(!BooleanUtils.isEmpty(result)){
//                suretextview.setVisibility(View.VISIBLE);
//                sellayout.setVisibility(View.VISIBLE);
//                seltextview.setText("已选择:"+showresult);
//            }else{
//                suretextview.setVisibility(View.INVISIBLE);
//                sellayout.setVisibility(View.GONE);
//                seltextview.setText("");
//            }
//            toast.showToast(result);
//            Log.d("TreeViewActivity","name----:"+name);
//            Log.d("TreeViewActivity","id----:"+id);
//            Log.d("TreeViewActivity","fathername----:"+fathername);
//            Log.d("TreeViewActivity","result----:"+result);
//        }else{//根节点
//            suretextview.setVisibility(View.INVISIBLE);
//            sellayout.setVisibility(View.GONE);
//            seltextview.setText("");
//        }
    }


    /**
     * 各种点击事件的方法
     * */


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.apptoplayout_withtextview_backlayout://返回
                finish();
                overridePendingTransition(0,R.anim.activity_right_open);
                break;
            case R.id.apptoplayout_withtextview_righttextview://确定添加
                toast.showToast("确定!");
                break;
        }
    }


    /**
     * onKeyDown方法
     * */


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(0,R.anim.activity_right_open);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}



猜你喜欢

转载自blog.csdn.net/weixin_37730482/article/details/79663610