Navigation menu implementation for Android drawer effect

Source: Internet
Author: User

Navigation menu for drawer effect

See a lot of applications, feel this slide-off drawer effect of the menu is very good.

You don't have to switch to another page, you don't have to press the hardware button on the menu, you just click on the button on the interface, the menu slides out, and you feel like you can put a lot of things.

On the implementation, search for a bit, like the following two kinds:

  1. Using Slidingdrawer:

Http://developer.android.com/reference/android/widget/SlidingDrawer.html

But don't know why this kind of official does not recommend to continue to use:

  Deprecated since API level 17

  2. Using drawerlayout:

Http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html

Guide is here:

Http://developer.android.com/training/implementing-navigation/nav-drawer.html

References to libraries

First of all, DrawerLayout This class is in the support library, need to add Android-support-v4.jar this package.

The import android.support.v4.widget.DrawerLayout is then imported in the program.

If this class is not found, first update the Android support Library with SDK Manager and then on Android sdk\extras\android\support\ Under the V4 path, locate Android-support-v4.jar, copy the Libs path to the project, and add it to Build path.

Code 1

Layout:

<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 "> <andr Oid.support.v4.widget.DrawerLayout xmlns: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-<!--main content must be the first element of Drawerlayout because it would be D            Rawn first and drawer must is on top of it and <framelayout android:id= "@+id/content_frame" Android:layout_width= "Match_parent" android:layout_height= "Match_parent"/> <!--the Navigati            On drawer--<listview android:id= "@+id/left_drawer" android:layout_width= "240DP"  android:layout_height= "Match_parent"          Android:layout_gravity= "left" android:background= "#111" android:choicemode= "Singlechoice" Android:divider= "@android: Color/transparent" android:dividerheight= "0DP"/> </android.suppo Rt.v4.widget.drawerlayout></relativelayout>

The first child element of Drawerlayout is the main content, which is the layout shown when the drawer is not open. A framelayout is used here, and nothing is left.

The second element of the drawerlayout is the contents of the drawer, the drawer layout, where a ListView is used.

Main activity (stripped from the official example):

Package Com.example.hellodrawer;import Android.os.bundle;import Android.app.activity;import Android.content.res.configuration;import Android.view.menuitem;import Android.view.view;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.arrayadapter;import Android.widget.listview;import Android.support.v4.app.ActionBarDrawerToggle; Import Android.support.v4.view.gravitycompat;import Android.support.v4.widget.drawerlayout;public class    Hellodraweractivity extends activity{private string[] mplanettitles;    Private Drawerlayout mdrawerlayout;    Private Actionbardrawertoggle Mdrawertoggle;    Private ListView mdrawerlist;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_hello_drawer);        Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout);   Init the ListView and Adapter, nothing new Initlistview ();     Set a custom shadow that overlays the main content when the drawer//opens Mdrawerlayout.setdrawers        Hadow (R.drawable.drawer_shadow, Gravitycompat.start);                Mdrawertoggle = new Actionbardrawertoggle (this, mdrawerlayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {/** Called when a drawer have settled in a completely closed stat E. */public void ondrawerclosed (view view) {Invalidateoptionsmenu ();///Creates CAL  L to//Onprepareoptionsmenu ()}/** called when a drawer Have settled in a completely open state. */public void ondraweropened (View drawerview) {invalidateoptionsmenu ();//Creates        Call to//Onprepareoptionsmenu ()}}; Set the drawer toggle as the DrawerlistenEr mdrawerlayout.setdrawerlistener (mdrawertoggle); Enable ActionBar app icon to behave as action to toggle nav drawer Getactionbar (). Setdisplayhomeasupenabled (True        );        Getactionbar (). Sethomebuttonenabled (True); Note:getactionbar () Added in API level one} private void Initlistview () {mdrawerlist = (ListView) fin        Dviewbyid (R.id.left_drawer);        Mplanettitles = Getresources (). Getstringarray (R.array.planets_array); Set the adapter for the list view Mdrawerlist.setadapter (new arrayadapter<string> (This, R.L        Ayout.list_item, Mplanettitles)); Set the list ' s click Listener mdrawerlist.setonitemclicklistener (New Onitemclicklistener () {@ Override public void Onitemclick (adapterview<?> parent, view view, int position, long             ID) {//Highlight the selected item, update the title, and close the   Drawer mdrawerlist.setitemchecked (position, true);                Settitle (Mplanettitles[position]);            Mdrawerlayout.closedrawer (mdrawerlist);    }        }); } @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 (new        Config);    Mdrawertoggle.onconfigurationchanged (Newconfig); } @Override public boolean onoptionsitemselected (MenuItem Item) {//Pass the event to Actionbardrawertogg Le, if it returns//true, then it has handled the app icon Touch event if (Mdrawertoggle.onoptionsitemselec        Ted (item)) {return true; }//Handle your other action bar items ... return Super.onoptionsitemselected (item); }}

The more tangled is the use of a level 11 API, so minsdkversion there is a limit, not too low.

Photo Resources Android Official website sample is available for download.

After the program runs the following effects:

  

Drawer before opening:

After opening the drawer:

Code 2

Today, I looked at the class of drawerlayout and found that there are many ways to use it directly.

Try again, in fact, do not have the above trouble, feel free to define a button control drawer open on the line:

Layout:

<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 "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Draweractivity "> <android.support.v4.widget.drawerlayout android:id=" @+id/drawer_layout "android:l        Ayout_width= "Match_parent" android:layout_height= "Match_parent" > <!--the main content view--            <framelayout android:id= "@+id/content_frame" android:layout_width= "Match_parent" android:layout_height= "Match_parent" > <button android:id= "@+id/btn" Androi D:layout_width= "Match_parent" Android: layout_height= "wrap_content" android:text= "open"/> </FrameLayout> <!--the navigation drawer---<listview android:id= "@+id/left_drawer" android:layou T_width= "240DP" android:layout_height= "match_parent" android:layout_gravity= "Start" Andro            Id:background= "#111" android:choicemode= "Singlechoice" android:divider= "@android: Color/transparent" android:dividerheight= "0DP"/> </android.support.v4.widget.DrawerLayout></RelativeLayout>

Main code:

Package Com.example.hellodrawer;import Android.os.bundle;import Android.app.activity;import Android.support.v4.widget.drawerlayout;import Android.view.gravity;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class Draweractivity extends Activity{    Private drawerlayout mdrawerlayout = null;    @Override    protected void onCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_drawer);        Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout);        Button button = (button) Findviewbyid (R.ID.BTN);        Button.setonclicklistener (New Onclicklistener ()        {            @Override public            void OnClick (View v)            {                Press the button to open the drawer                mdrawerlayout.opendrawer (Gravity.left);}}        );    }}

Resources

Official tutorials:

Http://developer.android.com/design/patterns/navigation-drawer.html

Http://developer.android.com/training/implementing-navigation/nav-drawer.html

Other references:

http://blog.chengyunfeng.com/?p=493

Http://my.eoe.cn/appadventure/archive/3826.html

Navigation menu implementation for Android drawer effect

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.