Open source Chinese source Learning (vii)--drawerlayout use

Source: Internet
Author: User

Drawerlayout is officially recommended by Google as a way to implement a side-by-side menu.

Open source China Oschina client and [email protected] the side-slip menu is implemented with the help of Drawerlayout. In the [email protected] project learning, just a cursory, since again met, it is necessary to summarize in detail.

The best textbook for learning Drawerlayout is Google's Official document--creating a Navigation Drawer

The use of Drawerlayout below is based on Google's Official document translation.

Brief introduction

The navigation drawer is a part of the screen that hides on the left edge of the display. It contains the main navigation options for the app. Most of the time it is hidden, but when the user's finger is gently sliding from the left edge of the screen to the right, the navigation screen will show up, or, at the top of the app, when the user clicks on the app icon in action Bar it will also appear.

Design of the navigation drawer

Before you decide to use the navigation drawer in your app, you have to understand the navigation drawer usage scenarios and design principles.

Create a drawer Layout

In order to add a navigation drawer, you need to declare an DrawerLayout object as the root node of the layout in your layout interface. DrawerLayoutadd two view in-house simultaneously:

  1. Add a view that contains the main content of the app (your main layout when the drawer is hidden);
  2. Add another view which contains the navigation drawer;

As shown in the following example: The layout uses Drawerlayout it contains two sub-nodes: One FrameLayout that contains the main content (which will be replaced by fragment at run time) and one ListView as the navigation drawer

<android.support.v4.widget.DrawerLayoutxmlns:android="http://schemas.android.com/ Apk/res/android "android:id=" @+id/drawer_layout "android:layout_width=" Match _parent "android:layout_height=" Match_parent ">                    <!--The main content view -    <framelayoutandroid:id="@+id/content_frame"android:layout_width= "Match_parent" android:layout_height="match_parent" />                            <!--The navigation drawer --    <listview  android:id  = "@+id/left_drawer"  android:layout_width
      = "240DP"  android:layout_height  = "match_parent"  android:layout_gravity  = "start"  android:choicemode  = " Singlechoice " android:divider  =" @android: Color/transparent " android:dividerheight  =" 0DP " android:background  =" #111 "/>< /span></android.support.v4.widget.DrawerLayout>

The above example contains some important layout tips:

    • Main content view (Framelayout on top) must be Drawerlayout the first child node because the XML is arranged in the order of the z-axis when the interface is arranged, the drawer must be at the top of the main content.
    • The main content view is set to match the width and height of the parent view, because it fills the entire UI when the navigation drawer is hidden.
    • The Navigation view (ListView) must be declared a horizontal gravity with the help of attributes android:layout_gravity . To satisfy a right-to-left convention, declare its value as "start" instead of "left" (so that the drawer will be rendered on the rightmost when the layout is RTL)
    • When navigating the View declaration: the width is in DP and the height matches the parent view. To ensure that users can see part of the main content in any way, the width of the navigation drawer cannot exceed 320DP
Initialize drawer List

The first thing to do in your activity is to initialize the list items in the navigation drawer. What to do depends on the content of your app, but the navigation drawer usually contains a ListView, so you also need a matching adapter (such as Arrayadapter or Simplecursoradapter)

The following example shows you how to use a string array to initialize a navigation list

 Public  class mainactivity extends Activity {    PrivateString[] Mplanettitles;PrivateDrawerlayout mdrawerlayout;PrivateListView mdrawerlist; ...@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Mplanettitles = Getresources (). Getstringarray (R.array.planets_array);        Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); Mdrawerlist = (ListView) Findviewbyid (r.id.left_drawer);//Set The adapter for the list viewMdrawerlist.setadapter (NewArrayadapter<string> ( This, R.layout.drawer_list_item, mplanettitles));//Set The list ' s click ListenerMdrawerlist.setonitemclicklistener (NewDraweritemclicklistener ()); ...    }}

The above code is called setOnItemClickListener() to accept the Click event in the Navigation list. The following shows how to implement this interface to change the main interface when the user selects an entry.

Handling Navigation Click events

When the user selects an entry in the drawer list, the system invokes the Onitemclick () method of the Onitemclicklistener object, provided the ListView is set to Setonitemclicklistener ().

What to do in the Onitemclick () method depends on how you want to implement your app structure. In the following example, each time an item is selected, a different fragment is inserted into the main interface (Framelayout elements are based on the R.id.content_frame)

Private  class Draweritemclicklistener implements ListView. Onitemclicklistener {    @Override     Public void Onitemclick(Adapterview parent, view view,intPositionLongID) {SelectItem (position); }}/** Swaps fragments in the main content view * /Private void SelectItem(intPosition) {//Create A new fragment and specify the planet to show based on positionFragment Fragment =NewPlanetfragment (); Bundle args =NewBundle ();    Args.putint (planetfragment.arg_planet_number, position); Fragment.setarguments (args);//Insert the fragment by replacing any existing fragmentFragmentmanager Fragmentmanager = Getfragmentmanager (); Fragmentmanager.begintransaction (). replace (R.id.content_frame, fragment). commit ();//Highlight The selected item, update the title, and close the drawermdrawerlist.setitemchecked (Position,true);    Settitle (Mplanettitles[position]); Mdrawerlayout.closedrawer (mdrawerlist);}@Override Public void Settitle(charsequence title)    {mtitle = title; Getactionbar (). Settitle (Mtitle);}
Listening for open and close events

To listen for the open and close events of the drawer, call Setdrawerlistener in your drawerlayout and pass it a drawerlayout.drawerlistener implementation. This interface provides callback methods for drawer events, such as: ondraweropened () and ondrawerclosed ().

However, it is not usually implemented Drawerlayout.drawerlistener, and if your activity contains the action Bar, you can inherit the Actionbardrawertoggle class. Actionbardrawertoggle implements Drawerlayout.drawerlistener, so you can still replicate the callback method above, but it really accelerates the action Bar icon and Interaction between navigation drawers (will be discussed in detail in the next section)

As discussed in the Navigation Drawer Design guide, when drawer is visible, you should modify the contents of the action bar, such as changing the title or removing the action items that are determined by the context of the main content interface.

The following code shows you how to override the Drawerlayout.drawerlistener callback method with the Actionbardrawertoggle instance:

 Public  class mainactivity extends Activity {    PrivateDrawerlayout mdrawerlayout;PrivateActionbardrawertoggle Mdrawertoggle;PrivateCharsequence Mdrawertitle;PrivateCharsequence Mtitle; ...@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        ... mtitle = Mdrawertitle = GetTitle ();        Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); Mdrawertoggle =NewActionbardrawertoggle ( This, Mdrawerlayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {/** Called when a drawer have settled in a completely closed state. * /             Public void ondrawerclosed(View view) {Super. ondrawerclosed (view);                Getactionbar (). Settitle (Mtitle); Invalidateoptionsmenu ();//Creates call to Onprepareoptionsmenu ()}/** Called when a drawer have settled in a completely open state. * /             Public void ondraweropened(View Drawerview) {Super. ondraweropened (Drawerview);                Getactionbar (). Settitle (Mdrawertitle); Invalidateoptionsmenu ();//Creates call to Onprepareoptionsmenu ()}        };//Set the drawer toggle as the DrawerlistenerMdrawerlayout.setdrawerlistener (Mdrawertoggle); }/* Called whenever we call Invalidateoptionsmenu () */    @Override     Public Boolean Onprepareoptionsmenu(Menu menu) {//If The nav drawer is open, hide action items related to the content view        BooleanDraweropen = Mdrawerlayout.isdraweropen (mdrawerlist); Menu.finditem (R.id.action_websearch). setvisible (!draweropen);return Super. Onprepareoptionsmenu (menu); }}

The following sections describe the construction parameters of the Actionbardrawertoggle and other steps that need to be set up to complete the interaction with the action Bar icon.

Open and close drawer with app Icon

The user can open or close the drawer to slide on the left edge of the screen, but if you use the action Bar, you should allow the user to open or close the drawer by touching the app icon. APP icon should also hint at navigation Drawer with a special icon. You can achieve all of these performances by using the actionbardrawertoggle shown in the previous section.

To ensure that the Actionbardrawertoggle works effectively, create an instance with its constructor, which requires the following parameters:

    • Holding Drawer's activity
    • Drawerlayout
    • Picture resource as a drawer indicator
    • A string resource describing the opening of a drawer
    • string resource describing the drawer closing

Then, whether or not you have created a actionbardrawertoggle subclass as your drawer listener, you need to call your actionbardrawertoggle in some places throughout the life cycle of your activity.

 Public  class mainactivity extends Activity {    PrivateDrawerlayout mdrawerlayout;PrivateActionbardrawertoggle Mdrawertoggle; ... Public void onCreate(Bundle savedinstancestate)        {... mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); Mdrawertoggle =NewActionbardrawertoggle ( This,/ * Host Activity * /Mdrawerlayout,/ * Drawerlayout Object * /R.drawable.ic_drawer,/ * NAV drawer icon to replace ' up ' caret * /R.string.drawer_open,/ * "Open drawer" description * /R.string.drawer_close/ * "Close drawer" description * /) {/** Called when a drawer have settled in a completely closed state. * /             Public void ondrawerclosed(View view) {Super. ondrawerclosed (view);            Getactionbar (). Settitle (Mtitle); }/** Called when a drawer have settled in a completely open state. * /             Public void ondraweropened(View Drawerview) {Super. ondraweropened (Drawerview);            Getactionbar (). Settitle (Mdrawertitle); }        };//Set the drawer toggle as the DrawerlistenerMdrawerlayout.setdrawerlistener (Mdrawertoggle); Getactionbar (). setdisplayhomeasupenabled (true); Getactionbar (). sethomebuttonenabled (true); }@Override    protected void onpostcreate(Bundle savedinstancestate) {Super. Onpostcreate (Savedinstancestate);//Sync the toggle state after onrestoreinstancestate have occurred.Mdrawertoggle.syncstate (); }@Override     Public void onconfigurationchanged(Configuration newconfig) {Super. onconfigurationchanged (Newconfig);    Mdrawertoggle.onconfigurationchanged (Newconfig); }@Override     Public Boolean onoptionsitemselected(MenuItem Item) {//Pass the event to Actionbardrawertoggle, if it returns        //True, then it has handled the app icon touch event        if(mdrawertoggle.onoptionsitemselected (item)) {return true; }//Handle Your other action bar items ...        return Super. onoptionsitemselected (item); }    ...}

At this point, the official document translation completed!

Summarize

The navigation drawer used in open source China is based on the official drawerlayout, and with the documentation above, you should be using Drawerlayout.

At the same time, I took this part to do a separate project, you can move my github download source code:

App_frame

Open source Chinese source Learning (vii)--drawerlayout use

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.