Use ListView to make multi-level menu

 
 

When developing Android, we need to make a multi-level tree menu, and the number of levels may change. I consulted many materials on the Internet and was greatly inspired. I found one on the Internet before, and completed the functional requirements at that time, but there are several problems. , I took out the original long code again today. After additions and deletions and my own understanding, I finally sorted it out.

Source resource download http://download.csdn.net/detail/op_kapu/5815691

The general idea: when you click on the parent node, add the child node to the listview and refresh the listview

When closing the parent node, delete the child node from the listview and refresh the listview

First picture:

 

Then the code~

TreeNode.java

package com.example.treetest;

import java.util.ArrayList;
import java.util.List;

/**
 * tree node object
 *
 * @author Kapu
 */
public class TreeNode {
	private String title;
	private boolean hasChildren;
	private int Level;
	private List<TreeNode> children = new ArrayList<TreeNode>();
	private boolean expanded;
	
	public void addChild(TreeNode node) {
		this.hasChildren = true;
		this.children.add(node);
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getLevel() {
		return Level;
	}

	public void setLevel(int level) {
		Level = level;
	}

	public boolean isExpanded() {
		return expanded;
	}

	public void setExpanded(boolean expanded) {
		this.expanded = expanded;
	}

	public boolean hasChildren() {
		return hasChildren;
	}

	public void hasChildren(boolean hasChildren) {
		this.hasChildren = hasChildren;
	}

	public List<TreeNode> getChildren() {
		return children;
	}

	public void setChildren(List<TreeNode> children) {
		this.hasChildren = true;
		this.children = children;
	}
}
TreeViewAdapter.java

package com.example.treetest;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class TreeViewAdapter extends BaseAdapter {  
	
    private LayoutInflater mInflater;  
    private List<TreeNode> mfilelist;  
    private Bitmap mIconCollapse; //- , Collapse
    private Bitmap mIconExpand; //+ , expand

    public TreeViewAdapter(Context context, List<TreeNode> treeNodes) {  
        super();  
        mInflater = LayoutInflater.from(context);  
        mfilelist = treeNodes;  
        mIconCollapse = BitmapFactory.decodeResource(context.getResources(), R.drawable.plus);  
        mIconExpand = BitmapFactory.decodeResource(context.getResources(), R.drawable.minus);  
    }  
    
	public int getCount() {  
        return mfilelist.size();  
    }  

	public Object getItem(int position) {  
        return position;  
    }  

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

	public View getView(int position, View convertView, ViewGroup parent) {  
        ViewHolder holder;  
        convertView = mInflater.inflate(R.layout.tree_node, null);  
        holder = new ViewHolder();  
        holder.text = (TextView) convertView.findViewById(R.id.treetext);  
        holder.icon = (ImageView) convertView.findViewById(R.id.icon);  
        convertView.setTag (holder);  

        final TreeNode obj = mfilelist.get(position);  

        int level = obj.getLevel();  
        holder.icon.setPadding(	15 * (level + 1),  
                holder.icon.getPaddingTop(), 0,  
                holder.icon.getPaddingBottom());  
        holder.text.setText(obj.getTitle());  
        if (obj.hasChildren()&& (obj.isExpanded() == false)) {  
            holder.icon.setImageBitmap(mIconCollapse);  
        } else if (obj.hasChildren() && (obj.isExpanded() == true)) {  
            holder.icon.setImageBitmap(mIconExpand);  
        } else if (!obj.hasChildren()) {  
            holder.icon.setImageBitmap(mIconCollapse);  
            holder.icon.setVisibility(View.INVISIBLE);  
        }  
        return convertView;  
    }  
    
    

    class ViewHolder {  
        TextView text;  
        ImageView icon;  

    }  
    
    
}
MainActivity.java

package com.example.treetest;

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.app.Activity;
public class MainActivity extends Activity{
    
	/** Left tree */
	private List<TreeNode> nodes = new ArrayList<TreeNode>();
	private TreeViewAdapter treeViewAdapter = null;
	/** Directory tree data */
	private ListView dir;
	/** The currently selected location in the left directory */
	int currentPosition;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        
        dir = (ListView) findViewById(R.id.dir);
		
		//Initialization data
        List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
        
        TreeNode tree0 = new TreeNode();
        tree0.setLevel(0);
        tree0.setTitle("Chapter 1");
        	List<TreeNode> treeNodeList0 = new ArrayList<TreeNode>();
        	TreeNode tree00 = new TreeNode();
            tree00.setLevel(1);
            tree00.setTitle("Lesson 1");
            
            TreeNode tree01 = new TreeNode();
            tree01.setLevel(1);
            tree01.setTitle("Second Lesson");
            		List<TreeNode> treeNodeList00 = new ArrayList<TreeNode>();
            		TreeNode tree000 = new TreeNode();
            		tree000.setLevel(2);
            		tree000.setTitle("The first section of the second lesson");
            		
            		TreeNode tree001 = new TreeNode();
            		tree001.setLevel(2);
            		tree001.setTitle("Second Lesson 2 Section 2");
            		treeNodeList00.add(tree000);
            		treeNodeList00.add(tree001);
            tree01.setChildren(treeNodeList00);	
            treeNodeList0.add(tree00);
            treeNodeList0.add(tree01);
        tree0.setChildren(treeNodeList0);
        tree0.hasChildren(true);
        
        TreeNode tree1 = new TreeNode();
        tree1.setLevel(0);
        tree1.setTitle("Chapter 2");
        
        treeNodeList.add(tree0);
        treeNodeList.add(tree1);
        
        nodes = treeNodeList;
        
		dir.setDivider(null);
        treeViewAdapter = new TreeViewAdapter(this, nodes);
		dir.setAdapter(treeViewAdapter);

		dir.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> l, View v, int position,
					long id) {
				
				// There is no child node under this node, that is, a section
				if (!nodes.get(position).hasChildren()) {
					return;
				}

				// If there is a child node under this parent node, and it has been expanded and closed, delete it
				if (nodes.get(position).isExpanded()) {
					nodes.get(position).setExpanded(false);
					TreeNode element = nodes.get(position); // Get the parent node first
 
					ArrayList<TreeNode> temp = new ArrayList<TreeNode>();
					// loop to get child nodes
					for (int i = position + 1; i < nodes.size(); i++) {
						if (element.getLevel() >= nodes.get(i).getLevel()) {
							break;
						}
						temp.add(nodes.get(i));
					}

					nodes.removeAll(temp);
					treeViewAdapter.notifyDataSetChanged();
				} else {
					// If the parent node is not expanded, it will be added when expanded
					TreeNode obj = nodes.get(position);
					obj.setExpanded(true);
					int level = obj.getLevel(); // parent node level
					int nextLevel = level + 1; // child node level = parent node level + 1
					int temp = position;//Temporary position
					// loop to get all child nodes of this parent node
					for (TreeNode element : obj.getChildren()) {
						element.setLevel(nextLevel);
						element.setExpanded(false);
					temp = temp+1;
						nodes.add(temp, element);
					}
					// refresh the list of changed nodes
					treeViewAdapter.notifyDataSetChanged();
				}
			}
		});
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521644&siteId=291194637