The implementation method of multi-level tree menu of Android improved _android

Source: Internet
Author: User

Generally in Android to implement the tree menu, are used Expandablelist (also have the master himself inherited ListView or LinearLayout to do), but expandablelist generally can only achieve level 2 tree-shaped menu. The examples described in this article still use Expandablelist, but the 3-level tree menu is being implemented.

The results of this program run as shown in the following illustration:

When you implement a level two tree menu with Baseexpandablelistadapter, the parent (Getgroupview ()) and subkeys (Getchildview ()) are all using TextView. When you want to implement a level three tree menu, the subkey (Getchildview ()) must use Expandablelist. In addition to defining the structure to facilitate the invocation of level three tree data, the level two tree menu can be used as follows:

static public class treenode{
 Object parent;
 List<object> childs=new arraylist<object> ();
}

The three-level tree menu can be used as follows, and the subkey is a hierarchy of level two tree menu, as shown in the following form:

Static public class Supertreenode {
 Object parent;
 The structural body of the second-order Tree menu is
 list<treeviewadapter.treenode> childs = new arraylist<treeviewadapter.treenode> ();
}

To achieve the level three tree menu, there are two points to note:

1, the second level is also a tree-shaped menu, it must be in the second level of project expansion/recycling to set enough space to fully display the level two tree menu;

2, in the implementation of the three-level tree menu, the discovery of the menu methods are not used (such as Onchildclicklistener, Ongroupclicklistener, etc.), so to get the selected data must be defined in the external callback function, The external function is then recalled when the level two tree menu is generated at the second level.

In addition, note: This article in the resolution of the No.2 key points, can only get the third level of the selected serial number. First, the second level is still unable to obtain its serial number.

Main.xml source code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:orientation=" vertical "android:layout_width=" fill_parent "
 android:layout_height=" Fill_parent ">
 <linearlayout android:id=" @+id/linearlayout01 "android:layout_width=" Wrap_content "
 android:layout_height= "Wrap_content" >
 <button android:layout_height= "wrap_content" android:text= "two-tier structure"
  android:layout_width= "160dip" android:id= "@+id/btnnormal" ></Button>
 <button Android:layout_ height= "Wrap_content" android:text= "three-layer structure"
  android:layout_width= "160dip" android:id= "@+id/btnsuper" ></ button>
 </LinearLayout>
 <expandablelistview android:id= "@+id/expandablelistview01"
 Android:layout_width= "Fill_parent" android:layout_height= "fill_parent" ></ExpandableListView>
< /linearlayout>

Testexpandablelist.java is the main class, calling other tool classes, the source code is as follows:

Package com.testexpandablelist;
Import java.util.List;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.ExpandableListView;
Import Android.widget.ExpandableListView.OnChildClickListener;
Import Android.widget.Toast;  The public class Testexpandablelist extends activity {/** called the ' when the ' is ' the activity ' is a-created
 Expandablelist;
 Treeviewadapter adapter;
 Supertreeviewadapter Superadapter;
  Button Btnnormal,btnsuper; Sample data set.
  Children[i] contains the children (string[]) for Groups[i].
  Public string[] groups = {"xxxx friend", "xxxx classmate", "xxxxx Woman"};
  Public string[][] child= {"A June", "B-June", "C-June", "D-June"}, {"Classmate a", "Classmate B", "Classmate C"}, {"Chinese", "Lori"}};
  Public string[] Parent = {"xxxx friend", "xxxx Classmate"};
    Public string[][][] child_grandson= {{"A June"}, {"AA", "AAA"}}, {{"B"}, {"BBB", "bbbb", "BBBBB"}}, {"C June"}, {"CCC"," CCCC "}}, {{" D-June "}, {" DDD "," DDDD "," DDDDD "}},};
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
    This.settitle ("Expandablelistview Practice----HELLOGV");
    Btnnormal= (Button) This.findviewbyid (r.id.btnnormal);
    Btnnormal.setonclicklistener (New Clickevent ());
    Btnsuper= (Button) This.findviewbyid (r.id.btnsuper);
    Btnsuper.setonclicklistener (New Clickevent ());
    Adapter=new Treeviewadapter (this,treeviewadapter.paddingleft>>1);
    Superadapter=new Supertreeviewadapter (this,stvclickevent);
  Expandablelist= (Expandablelistview) testExpandableList.this.findViewById (R.ID.EXPANDABLELISTVIEW01); Class Clickevent implements view.onclicklistener{@Override public void OnClick (View v) {adapter.
  RemoveAll ();
  Adapter.notifydatasetchanged ();
  Superadapter.removeall ();
  
  Superadapter.notifydatasetchanged (); if (v==btnnormal) {list<treeviewadapter.treenode>TreeNode = adapter.
     Gettreenode ();
      for (int i=0;i<groups.length;i++) {treeviewadapter.treenode node=new treeviewadapter.treenode ();
      Node.parent=groups[i];
      for (int ii=0;ii<child[i].length;ii++) {node.childs.add (child[i][ii]);
     } treenode.add (node); } adapter.   
     Updatetreenode (TreeNode);
     Expandablelist.setadapter (adapter); Expandablelist.setonchildclicklistener (New Onchildclicklistener () {@Override public boolean onchildclick (expandable ListView arg0, View arg1, int parent, int children, long Arg4) {String str= "Parent ID:" +string.valueof (parent) + ", CH
   Ildren ID: "+string.valueof (children);"
   Toast.maketext (Testexpandablelist.this, str, +). Show ();
   return false;
  }
     });
     else if (v==btnsuper) {list<supertreeviewadapter.supertreenode> Supertreenode = Superadapter.gettreenode (); for (int i=0;i<parent.length;i++)//First layer {Supertreeviewadapter.supertreenode Supernode=neW Supertreeviewadapter.supertreenode ();
      
      Supernode.parent=parent[i]; The second layer for (int ii=0;ii<child_grandson.length;ii++) {Treeviewadapter.treenode node=new Treeviewadap ter.
        TreeNode (); node.parent=child_grandson[ii][0][0];//the title for the second level menu for (int iii=0;iii<child_grandson[ii][1].length;iii++)/
        /Level III Menu {NODE.CHILDS.ADD (CHILD_GRANDSON[II][1][III]);
       } superNode.childs.add (node);
     } supertreenode.add (Supernode);
     } superadapter.updatetreenode (Supertreenode);
  Expandablelist.setadapter (Superadapter); The event for the/** * Level three tree menu is no longer available, and this function is being recalled by a child of level three tree menu (Level two menu)/Onchildclicklistener stvclickevent=new Onchildclickliste
  NER () {@Override public boolean Onchildclick (expandablelistview parent, View v, int groupposition, int childposition,
  Long ID {String str= "Parent ID:" +string.valueof (groupposition) + ", Children ID:" +string.valueof (childposition); Toast.maketext (tesTexpandablelist.this, str, (). Show ();
 return false;
}
  };

 }

The

Treeviewadapter.java is the tool class that implements the level two tree menu, the source code is as follows:

Package com.testexpandablelist;
Import java.util.ArrayList;
Import java.util.List;
Import Android.content.Context;
Import Android.util.Log;
Import android.view.Gravity;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.AbsListView;
Import Android.widget.BaseExpandableListAdapter;
Import Android.widget.TextView; public class Treeviewadapter extends baseexpandablelistadapter{public static final int itemheight=48;//height public STA for each item TIC Final int paddingleft=36;//the height of each item private int mypaddingleft=0;//If called by Supertreeview, move the static public class Tr to the right as a subkey
 eenode{Object Parent;
 List<object> childs=new arraylist<object> ();
 } list<treenode> treenodes = new arraylist<treenode> ();
 Context Parentcontext;
 Public Treeviewadapter (Context View,int mypaddingleft) {parentcontext=view;
 This.mypaddingleft=mypaddingleft;
 Public list<treenode> Gettreenode () {return treenodes; } public void Updatetreenode (list<treenode> noDES) {treenodes=nodes;
 public void RemoveAll () {treenodes.clear (); Public Object getchild (int groupposition, int childposition) {return treenodes.get (groupposition). Childs.get (Childpo
 Sition);
 public int Getchildrencount (int groupposition) {return treenodes.get (groupposition). Childs.size (); Static public TextView Gettextview {abslistview.layoutparams LP = new Abslistview.layoutparams (Vi
 EwGroup.LayoutParams.FILL_PARENT, ItemHeight);
 TextView TextView = new TextView (context);
 TEXTVIEW.SETLAYOUTPARAMS (LP); Textview.setgravity (gravity.center_vertical |
 Gravity.left);
 return textView; Public View getchildview (int groupposition, int childposition, Boolean islastchild, View Convertview, ViewGroup paren
 T) {TextView TextView = Gettextview (This.parentcontext);
 Textview.settext (Getchild (Groupposition, childposition). toString ());
 Textview.setpadding (mypaddingleft+paddingleft, 0, 0, 0);
 return textView; Public View getgroupview (int gRoupposition, Boolean isexpanded, View Convertview, ViewGroup parent) {TextView TextView = Gettextview (this.parentcont
 EXT);
 Textview.settext (Getgroup (groupposition). toString ());
 Textview.setpadding (mypaddingleft+ (paddingleft>>1), 0, 0, 0);
 return textView;
 public long Getchildid (int groupposition, int childposition) {return childposition;
 Public Object getgroup (int groupposition) {return treenodes.get (groupposition). Parent;
 public int GetGroupCount () {return treenodes.size ();
 public long getgroupid (int groupposition) {return groupposition;
 public boolean ischildselectable (int groupposition, int childposition) {return true;
 public Boolean hasstableids () {return true;

 }
}

The

Supertreeviewadapter.java is the tool class that implements the level three tree menu, will use the Treeviewadapter.java, the source code is as follows:

Package com.testexpandablelist;
Import java.util.ArrayList;
Import java.util.List;
Import Com.testExpandableList.TreeViewAdapter.TreeNode;
Import Android.content.Context;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.AbsListView;
Import Android.widget.BaseExpandableListAdapter;
Import Android.widget.ExpandableListView;
Import Android.widget.ExpandableListView.OnChildClickListener;
Import Android.widget.ExpandableListView.OnGroupCollapseListener;
Import Android.widget.ExpandableListView.OnGroupExpandListener;
Import Android.widget.TextView; 
 public class Supertreeviewadapter extends Baseexpandablelistadapter {static public class Supertreenode {Object parent;
 The structural body of the second-order Tree menu is list<treeviewadapter.treenode> childs = new arraylist<treeviewadapter.treenode> ();
 Private list<supertreenode> supertreenodes = new arraylist<supertreenode> ();
 Private context Parentcontext; Private Onchildclicklistener stvclickevent;//External callback function public SUpertreeviewadapter (Context View,onchildclicklistener stvclickevent) {parentcontext = view;
 This.stvclickevent=stvclickevent;
 Public list<supertreenode> Gettreenode () {return supertreenodes;
 public void Updatetreenode (list<supertreenode> node) {supertreenodes = node;
 public void RemoveAll () {supertreenodes.clear (); Public Object getchild (int groupposition, int childposition) {return supertreenodes.get (groupposition). Childs.get (Ch
 Ildposition);
 public int Getchildrencount (int groupposition) {return supertreenodes.get (groupposition). Childs.size (); Public Expandablelistview Getexpandablelistview () {abslistview.layoutparams LP = new Abslistview.layoutparams (View
 Group.LayoutParams.FILL_PARENT, Treeviewadapter.itemheight);
 Expandablelistview Supertreeview = new Expandablelistview (parentcontext);
 SUPERTREEVIEW.SETLAYOUTPARAMS (LP);
 return supertreeview; The second layer of the/** * Three-layer tree structure is a expandablelistview/public View getchildview (int Groupposition, int childposition, Boolean islastchild, View Convertview, ViewGroup parent) {//is final Expandablelistview t
 Reeview = Getexpandablelistview ();
 Final Treeviewadapter treeviewadapter = new Treeviewadapter (this.parentcontext,0); list<treenode> tmp = Treeviewadapter.gettreenode ();//temporary variable gets the TreeNode collection of Treeviewadapter, which can be null final TreeNode
 Treenode= (TreeNode) getchild (groupposition, childposition);
 Tmp.add (TreeNode);
 Treeviewadapter.updatetreenode (TMP);
 Treeview.setadapter (Treeviewadapter);
 Key point: Gets the parent-child node of the selected level two tree menu, and returns the result to the external callback function Treeview.setonchildclicklistener (this.stvclickevent);
  /** * Key point: The second level menu expands by obtaining the number of nodes to set the size of the third level menu * * * Treeview.setongroupexpandlistener (new Ongroupexpandlistener () {@Override public void Ongroupexpand (int groupposition) {abslistview.layoutparams LP = new Abslistview.layoutparams (viewgroup .
  Layoutparams.fill_parent, (TreeNode.childs.size () +1) *treeviewadapter.itemheight + 10);
  TREEVIEW.SETLAYOUTPARAMS (LP);
 }
 }); /** * Second-level menu collection is set to superscriptQuasi Item size */Treeview.setongroupcollapselistener (new Ongroupcollapselistener () {@Override public void ongroupcollaps 
   E (int groupposition) {abslistview.layoutparams LP = new Abslistview.layoutparams (ViewGroup.LayoutParams.FILL_PARENT,
  Treeviewadapter.itemheight);
  TREEVIEW.SETLAYOUTPARAMS (LP);
 }
 });
 Treeview.setpadding (treeviewadapter.paddingleft, 0, 0, 0);
 return treeView; The first layer in the/** * Level three tree structure is TextView, used as title/public View getgroupview (int groupposition, Boolean isexpanded, View convert
 View, ViewGroup parent) {TextView TextView = Treeviewadapter.gettextview (This.parentcontext);
 Textview.settext (Getgroup (groupposition). toString ());
 Textview.setpadding (treeviewadapter.paddingleft, 0, 0, 0);
 return textView;
 public long Getchildid (int groupposition, int childposition) {return childposition;
 Public Object getgroup (int groupposition) {return supertreenodes.get (groupposition). Parent;
public int GetGroupCount () {return supertreenodes.size (); public long getgroupid (int groupposition) {return groupposition;
 public boolean ischildselectable (int groupposition, int childposition) {return true;
 public Boolean hasstableids () {return true;

 }
}

To sum up, some bugs are hard to solve when using expandablelist to implement level three tree menus, and you need to be careful when defining three-dimensional arrays! So try to simplify the data to use the level two tree menu.

I hope the code described in this article will help you with the Android program.

Related Article

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.