Android Implementation Horizontal level two menu _android

Source: Internet
Author: User
Tags addall

The example of this article is to share the Android two level horizontal menu implementation process. The effect is as above:

This horizontal level two menu is applied to many apps. The effect is still very beautiful. It is also a project needs, I also learned the effect of this, first of all, to say logic. The way to do this is not really difficult. But logically it may be a little complicated. The principle is actually a button. When the trigger button pops up, the Popwindow.popwindow is composed of two ListView. Suitable fit for two ListView. This effect can be achieved.

There are two different ways to achieve this effect. One is to write directly in the layout file Layout.xml ... The top can be a button, or it can be more than one button. Multiple buttons can be implemented using Radiogroup. The bottom is to use ScrollView to achieve is also possible.

But let me just say the second way. Write this layout directly in Java. Implement this effect by using a custom control ... Since it's a custom, first we need to inherit a layout. The layout can use LinearLayout or relativelayout.

SetValue () method.

The SetValue () method is a custom method ... It is mainly used to load the layout. and add related view to the layout. No XML file is loaded ...

  /** * @param the set of text values for item in Textarray:listview. 
   * @param viewarray: View that needs to be added to the current layout. * */@SuppressLint ("Resourceascolor") public void SetValue (arraylist<string> textarray, arraylist<view> v
    Iewarray) {if (Mcontext = = null) {return;

    } layoutinflater Inflater = (layoutinflater) mcontext.getsystemservice (Context.layout_inflater_service);
    Mtextlist = Textarray;
      for (int i = 0; i < viewarray.size (); i++) {//This adds a view ...
      Final Relativelayout r = new Relativelayout (mcontext);  int maxheight = (int) (displayheight * 0.5);
      
      
      Define the height of the layout ... Relativelayout.layoutparams RL = new Relativelayout.layoutparams (RelativeLayout.LayoutParams.MATCH_PARENT,
      MaxHeight); R.addview (Viewarray.get (i), RL);
      Add a view to the layout and specify the parameter Mviewlist.add (r);
      
      R.settag (SMALL); Define the topmost button and add the button to the layout. and set the button's text ToggleButton TButton = (ToggleButton) inflater.inflate (R.layoUt.toggle_button, this, false);
      AddView (TButton);
      Mtogglelist.add (TButton);
      Tbutton.settag (i);
      
      Tbutton.settext (Mtextlist.get (i)); Used to implement when Popwindow is displayed. Click Back Again Popwindow r.setonclicklistener (new Onclicklistener () {@Override public vo
        ID OnClick (View v) {onpressback ();

      }
      });
      
      R.setbackgroundcolor (Mcontext.getresources (). GetColor (R.color.popup_main_background)); The Listener Tbutton.setonclicklistener (new Onclicklistener () {@Override public void OnClick (Vi) When the button is clicked
          EW view) {ToggleButton TButton = (ToggleButton) view;
            /** if the currently clicked button is different from the last click, set the current button to be in the click state/if (Selectedbutton!= null && selectedbutton!= TButton) {
          Selectedbutton.setchecked (FALSE);
          } Selectedbutton = TButton;
          Selectposition = (Integer) selectedbutton.gettag ();
          When the/** button is clicked, the corresponding listener event needs to be triggered.Startanimation (); if (Monbuttonclicklistener!= null && tbutton.ischecked ()) {Monbuttonclicklistener.onclick (Selectposi
          tion);
    }
        }
      });
 }
  }

After you have finished styling the layout ... There is only one ToggleButton button. After clicking, there is no effect. We need to define a new view. The pop-up window that you need to display when you click the button. then this pop-up window needs to be customized.

The pop-up window is displayed in two ListView form. Add two listview to the layout. Set the appropriate adapter for each ListView. Then add the view to the main view above. You can implement the effect of the pop-up window displayed below when the button is clicked ..

Childview () How the layout of pop-up view is implemented ...

This view is defined here, and the corresponding initialization is done. Setting the corresponding adapter is complete.

Package Com.example.view;
Import java.util.ArrayList;

Import java.util.LinkedList;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.util.SparseArray;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.widget.LinearLayout;

Import Android.widget.ListView;
Import Com.example.adapter.TextAdapter;

Import COM.EXAMPLE.EXPANDTABVIEW.R;  public class Childview extends LinearLayout {private ListView regionlistview;  The main ListView private ListView Platelistview;
      Sub ListView//main ListView Each item corresponds to the text private String leftfastring[] = new string[] {"Gourmet", "fast food Snack", "hotpot", "Seafood/barbecue",
  "Special dishes", "fragrant pot/Grilled fish", "local cuisine", "Southeast Asian Cuisine", "Western Food", "Japanese and Korean cuisine"}; Child ListView Each item corresponds to the text.
  The implementation of two-dimensional array is adopted. Private String leftch1string[][] = new string[][] {{All}, {"All", "Chinese Simple Meal", "local snacks", "rice bowls", "rice noodles", "noodle Shop", "spicy Hot "," braised chicken rice with yellow sauce "," duck Neck and lo mei "," Dumplings wonton "," Fried chicken skewers "," steamed stuffed bun/porridge "," snack "," Fried dumpling "," vegetables "}, {" All "," Other Hotpot "}, {" All "," crayfish "}, {" All Department "}, {" All"," fragrant pot "," Grilled Fish "}, {" All "," Shandong Cuisine "," "Sichuan cuisine", "other"}, {"All"}, {"All", "spaghetti Pizza", "Western fast Food", "other Western Cuisine"}, {"All", "Korean Simple Meal", "Korean cuisine

  " } };
  
  Add data information in the main listview private arraylist<string> groups = new arraylist<string> ();
  
  Add data information in a ListView private linkedlist<string> Childrenitem = new linkedlist<string> (); Sparse array Private sparsearray<linkedlist<string>> children = new Sparsearray<linkedlist<string>
  > ();
  Set adapter Private Textadapter Platelistviewadapter for ListView;
  Private Textadapter Earalistviewadapter;
  
  The setting of the listening event private Onselectlistener Monselectlistener;   private int tearaposition = 0;
  Used to hold the position of the item that the current main ListView is clicked on.    private int tblockposition = 0;
  
  Used to hold the position of the item that the current child ListView is clicked on.

  Private String showstring = "";
    Public Childview {Super (context);
  Init (context);
    Public Childview (context, AttributeSet attrs) {Super (context, attrs);
Init (context);  } private void Init (context context) {Layoutinflater Inflater = (layoutinflater) context. Getsystemserv
    
    Ice (Context.layout_inflater_service);
    Load layout, binding ID.
    Inflater.inflate (R.layout.view_region, this, true);
    Regionlistview = (ListView) Findviewbyid (R.id.listview);

    Platelistview = (ListView) Findviewbyid (R.ID.LISTVIEW2);
      Initializes the text for (int i=0;i<10;i++) {groups.add (leftfastring[i]) corresponding to each item in the ListView;
      linkedlist<string> TItem = new linkedlist<string> ();
        
      for (int j=0;j<leftch1string[i].length;j++) {titem.add (leftch1string[i][j]);
    } children.put (I, TItem); }//Main ListView list Item Adapter Earalistviewadapter = new Textadapter (context, groups, R.drawable.choose, R.
    Drawable.choose_eara_item_selector);
    Earalistviewadapter.settextsize (12);
    
    Earalistviewadapter.setselectedpositionnonotify (tearaposition); Regionlistview.setadapter (EaralistviewadApter);
          Earalistviewadapter. Setonitemclicklistener (New Textadapter.onitemclicklistener () {@Override public void Onitemclick (view view, int position) {if (Position < Children.size ()) {Childre
              Nitem.clear (); Get all the data information for this page ...
              Then wake up the adapter to update the data Childrenitem.addall (Children.get (position));
            Platelistviewadapter.notifydatasetchanged ();
    
    }
          }
        });
    
    
    if (Tearaposition < Children.size ()) Childrenitem.addall (Children.get (tearaposition));
        ListView Adapter Platelistviewadapter = new Textadapter (context, Childrenitem, R.drawable.choose_item_right,
    R.drawable.choose_plate_item_selector);
    Platelistviewadapter.settextsize (12);
    Platelistviewadapter.setselectedpositionnonotify (tblockposition);
    Platelistview.setadapter (Platelistviewadapter);
    Sets the listener that triggers when item is clicked. Platelistviewadapter. SetonitemclicklisTener (New Textadapter.onitemclicklistener () {@Override public void Onitemclick (view view, Final int
            Position) {//Get the text data of the item clicked Showstring = Childrenitem.get (position);
            if (Monselectlistener!= null) {Monselectlistener.getvalue (showstring);
    
    }

          }
        });
    if (Tblockposition < Childrenitem.size ()) showstring = Childrenitem.get (tblockposition);

  Setdefaultselect ();
  //Set the position of the current item.
    public void Setdefaultselect () {//Default selected item Item regionlistview.setselection (tearaposition);
  Platelistview.setselection (tblockposition);
  Public String Getshowtext () {return showstring;
  public void Setonselectlistener (Onselectlistener onselectlistener) {monselectlistener = Onselectlistener;
  Public interface Onselectlistener {public void GetValue (String showtext);

 }

}

Then finally the adapter is left.

Arrayadapter<string>

The Arrayadapter adapter is used here. Inheritance and baseadapter. Can be used to display text data ... We also know that the method that adapters must implement is the GetView () method. So let's take a quick look at this method.

  @SuppressLint ("Resourceascolor") @SuppressWarnings ("deprecation") @Override public view GetView (int position, view
    Convertview, ViewGroup parent) {TextView view; if (Convertview = = null) {view = (TextView) layoutinflater.from (Mcontext). Inflate (R.layout.choose_item, parent, FAL
    SE);
    else {view = (TextView) Convertview;
    } view.settag (position);
    String mstring = "";
      if (mlistdata!= null) {if (Position < Mlistdata.size ()) {mstring = Mlistdata.get (position); } else if (Marraydata!= null) {if (position < marraydata.length) {mstring = Marraydata[position]
      ;
    } if (Mstring.contains ("unlimited")) View.settext ("unlimited");
    else View.settext (mstring);

    View.settextsize (typedvalue.complex_unit_sp,textsize); if (selectedtext!= null && selectedtext.equals (mstring)) {view.setbackgrounddrawable (selecteddrawble);//Set Selected background picture} else {View.setbackgroundDrawable (Mcontext.getresources (). getdrawable (Normaldrawbleid));/Set unselected background picture} view.setpadding (20, 0, 0, 0);
    View.setonclicklistener (Onclicklistener);
  return view;
 }

The matching job is very simple. Just a textview can be done. Of course, we can also write a more complex style. Define some complex controls within a layout. You can achieve better results.

Finally mainactivity the layout file in the load this control, simple to do some initialization operation can be achieved.

Package Com.example.expandtabview;

Import java.util.ArrayList;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;

Import Android.widget.Toast;
Import Com.example.view.ExpandTabView;

Import Com.example.view.ChildView;
  public class Mainactivity extends activity {private Expandtabview Expandtabview;
  Private arraylist<view> Mviewarray = new arraylist<view> ();
  
  Private Childview Viewleft;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Initview ();
    Initvaule ();
    
  Initlistener ();
    private void Initview () {//Initialize control Expandtabview = (Expandtabview) Findviewbyid (R.id.expandtab_view);
    
  Viewleft = new Childview (this);
    
    private void Initvaule () {mviewarray.add (viewleft);
    Set top data information arraylist<string> Mtextarray = new arraylist<string> (); Mtextarray.add("All");
    Expandtabview.setvalue (Mtextarray, Mviewarray);
    
  Expandtabview.settitle (Viewleft.getshowtext (), 0);
      
      private void Initlistener () {Viewleft.setonselectlistener () {new Childview.onselectlistener () {
        
      @Override public void GetValue (String showtext) {Onrefresh (viewleft,showtext);
    
    
  }
    });
    }//The view is clicked after the data is refreshed private void Onrefresh (view view, String Showtext) {expandtabview.onpressback ();
    int position = Getpositon (view); if (position >= 0 &&!expandtabview.gettitle (position). Equals (Showtext)) {Expandtabview.settitle (Showtex
    T, position);

  } toast.maketext (Mainactivity.this, Showtext, Toast.length_short). Show (); //Get the current view private int Getpositon (view tview) {for (int i = 0; i < mviewarray.size (); i++) {if (M
      Viewarray.get (i) = = Tview) {return i;
  }} return-1;

 }
}

Here's just some core code. Some of the other unimportant code involved is not pasted here. Finally put a picture flow. It's easy for everyone to understand. Finally, the source code is given.

Put a source code to provide downloads to facilitate understanding of this process:Android to achieve horizontal level two menu

The above is the entire content of this article, I hope to help you learn.

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.