Tree List in Android

Source: Internet
Author: User

Tree list front-end is very common, but also someone specifically wrote ztree,android in some cases also need to use the tree-like list, the previous article wrote about Expandablelistview,expandablelistview support for up to two levels of structure, Android does not have a three-tier component, and this time it needs to expand itself, expand the Expandablelistview, and optionally expand the ListView. Personal feel to expand the ListView more simple, multilevel list you can be loaded out at once, can also be graded loaded out, the general classification is better, point at a certain level can control click events and then to load the children, so that the implementation will be easy, or understand a little.

Basic Maintenance

Create a new Activity_tree.xml layout file with a separate listview:

<relativelayout 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 "    tools:context= "com.example.googletree.TreeActivity" >  <listview         android:id= "@+id/tree_list"        android:layout_width= "match_parent"        android:layout_height= "Match_parent"/></relativelayout>

Tree_item layout file, which includes a picture, a text:

<?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=" match_parent ">           < ImageView         android:id= "@+id/homeimg"        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:layout_centervertical=" true "        android:layout_alignparentleft=" true "/>        < TextView         android:id= "@+id/treetext"        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:layout_centervertical=" true "        android:layout_torightof=" @id/homeimg "/>    </RelativeLayout>
Demo implementation

Need to show a tree structure of the data, first define a TreeNode class, you need to show the data which is mainly about the next few fields, the relationship between the parent and the child you can use the ParentID judgment can also be used to distinguish between the code to see a person's preferences:

Text: ContentText

ID Number: ID

ParentID: Parent ID

HasChildren: Judging is not the last level

Isexpanded:item whether to expand

public class TreeNode {/** literal content */private String contenttext;/** in the tree hierarchy */private int level;/** element ID */private int ID; /** the ID of the parent element */private int parendid;/** Whether there are child elements */private Boolean haschildren;/** Item expands */private boolean isexpanded;/** table Indicates that the node has no parent element, that is, a node of level 0 */public static final int no_parent = -1;/** means that the element is at the topmost layer */public static final int top_level = 0 ;p ublic TreeNode (String contenttext, int level, int id, int parendid,boolean haschildren, Boolean isexpanded) {super (); thi S.contenttext = Contenttext;this.level = Level;this.id = Id;this.parendid = Parendid;this.haschildren = HasChildren;this . isexpanded = isexpanded;} public Boolean isexpanded () {return isexpanded;} public void setexpanded (Boolean isexpanded) {this.isexpanded = isexpanded;} Public String Getcontenttext () {return contenttext;} public void Setcontenttext (String contenttext) {this.contenttext = ContentText;} public int Getlevel () {return level;} public void SetLevel (Int. level) {this.level = level;} public int GetId () {REturn ID;} public void setId (int id) {this.id = ID;} public int Getparendid () {return parendid;} public void Setparendid (int parendid) {this.parendid = Parendid;} public Boolean Ishaschildren () {return haschildren;} public void Sethaschildren (Boolean haschildren) {this.haschildren = HasChildren;}}

  in order to populate the ListView in the view, you need to customize Treeadapter, Previous articles about the use of adapter in the ListView have been introduced, if you need to use specific how to see the previous article, the main use of a Viewholder optimization:

public class Treeadapter extends Baseadapter {/** All data collection */private arraylist<treenode> allnodes;/** top-level elements combined */ Private arraylist<treenode> topnodes;/** layoutinflater */private layoutinflater inflater;/** The beginning of the item indent base */ private int indentionbase;public Treeviewadapter (arraylist<treenode> topnodes, arraylist<treenode> Allnodes, Layoutinflater inflater) {this.topnodes = Topnodes;this.allnodes = Allnodes;this.inflater = Inflater; Indentionbase = 20;} Public arraylist<treenode> Gettopnodes () {return topnodes;} Public arraylist<treenode> Getallnodes () {return allnodes;} @Overridepublic int GetCount () {return topnodes.size ();} @Overridepublic Object getItem (int position) {return topnodes.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Convertview = = null) {holder = new Viewholder (); Convertview = Inflater.inflate (r.layout.tree_itEM, null); holder.homeimg = (ImageView) Convertview.findviewbyid (r.id.homeimg); holder.treetext = (TextView) Convertview.findviewbyid (R.id.treetext); Convertview.settag (holder);} else {holder = (Viewholder) Convertview.gettag ();} TreeNode element = Topnodes.get (position); int level =element.getlevel (); Holder.homeImg.setPadding (Indentionbase * ( Level + 1), Holder.homeImg.getPaddingTop (), Holder.homeImg.getPaddingRight (), Holder.homeImg.getPaddingBottom ()); Holder.treeText.setText (Element.getcontenttext ()); if (Element.ishaschildren () &&!element.isexpanded ()) { Holder.homeImg.setImageResource (R.drawable.open),///here to actively set the icon is visible, because Convertview may be reused "set up invisible" view, the same below. Holder.homeImg.setVisibility (view.visible);} else if (Element.ishaschildren () && element.isexpanded ()) {Holder.homeImg.setImageResource (R.drawable.open) ; holder.homeImg.setVisibility (view.visible);} else if (!element.ishaschildren ()) {Holder.homeImg.setImageResource (r.drawable.open); holder.homeImg.setVisibility (View.visiBLE);} return Convertview;} Static class Viewholder{imageview homeimg; TextView Treetext;}}

Because each time a layer of nodes is loaded, you need to control the click events, Customizing a Treeitemclicklistener to listen for events:

public class Treeitemclicklistener implements Onitemclicklistener {/**-defined adapter */private treeviewadapter treeviewadapter ;p ublic Treeviewitemclicklistener (treeviewadapter treeviewadapter) {this.treeviewadapter = TreeViewAdapter;} @Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long ID) {//Click on the item that represents the element TreeNode TreeNode = (TreeNode) treeviewadapter.getitem (position);//The element in the top layer of the tree arraylist<treenode> topnodes = Treeviewadapter.gettopnodes ();//The data source of the element arraylist<treenode> Allnodes = Treeviewadapter.getallnodes ();// Click on the item without the subkey to return directly if (!treenode.ishaschildren ()) {return;} if (treenode.isexpanded ()) {treenode.setexpanded (false);//delete node internal corresponding child node data, including child nodes of child nodes ... arraylist<treenode> Elementstodel = new arraylist<treenode> (); for (int i = position + 1; i < topnodes.size ( ); i++) {if (Treenode.getlevel () >= topnodes.get (i). Getlevel ()) Break;elementstodel.add (Topnodes.get (i));} Topnodes.removeall (Elementstodel); treeviewadapter.notifydatasetchanged ();} ELSE {treenode.setexpanded (TRUE);//extract child node data from the data source to add to the tree, note that this is just adding the next level of child nodes, in order to simplify the logic int i = 1;//Note here The counter is placed on the for outside to ensure that the count is valid for ( TreeNode e:allnodes) {if (e.getparendid () = = Treenode.getid ()) {e.setexpanded (false); Topnodes.add (position + I, e); i + +; }}treeviewadapter.notifydatasetchanged ();}}}

private void Init () {topnodes = new arraylist<treenode> (); allnodes = new arraylist<treenode> ();//Add node--node name , node level, node ID, parent node ID, whether there are child nodes, expand//Add outermost node TreeNode node1= new TreeNode ("Beijing", Treenode.top_level, 0, Treenode.no_ PARENT, True, false);//Add first-level node TreeNode node2= new TreeNode ("Haidian", Treenode.top_level + 1, 1, Node1.getid (), True, false); /Add second-tier node TreeNode node3= new TreeNode ("West Two Flags", Treenode.top_level + 2, 2, Node2.getid (), True, false);//Add a third-tier node//treenode no de7= New TreeNode ("Brilliant International", Treenode.top_level + 3, 6, Node3.getid (), false, false);//Add first-level node TreeNode node4= new TreeNode ("River South Province ", Treenode.top_level, 3, Treenode.no_parent, True, false);//Add a second-tier node TreeNode node5= new TreeNode (" Zhengzhou ", Treenode.top_ Level + 1, 4, Node4.getid (), True, false);//Add a third-tier node TreeNode node6= new TreeNode ("Jinshui", Treenode.top_level + 2, 5, node5.ge TId (), false, false);//Add initial tree element Topnodes.add (node1); Topnodes.add (NODE4);//Create Data source Allnodes.add (Node1); Allnodes.add ( Node2); Allnodes.add (NODE3); Allnodes.add (NODE4); allNodes.Add (NODE5); Allnodes.add (node6);//allnodes.add (NODE7);} 

Called in the OnCreate method:

Layoutinflater Inflater = (layoutinflater) getsystemservice (Context.layout_inflater_service); init (); ListView TreeView = (ListView) Findviewbyid (R.id.tree_list); Treeviewadapter treeviewadapter = new Treeviewadapter (Topnodes, Allnodes, Inflater); Treeviewitemclicklistener Treeviewitemclicklistener = new Treeviewitemclicklistener (treeViewAdapter); Treeview.setadapter (Treeviewadapter); Treeview.setonitemclicklistener (Treeviewitemclicklistener);

The effect is as follows:

Expand All:

This time the Node7 annotation in the treeactivity is canceled, that is, the effect of adding a third layer of nodes:

TreeNode node7= New TreeNode ("Brilliant International", Treenode.top_level + 3, 6, Node3.getid (), false, false);

The effect is as follows:

Tree List in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.