Drawerlayout drawer effect in Android app menu writing example _php tips

Source: Internet
Author: User

Navigation menu for drawer effect
looking at a lot of applications, I think this slippery drawer effect of the menu is very good.

Do not have to switch to another page, also do not have to press the menu hardware button, directly in the interface of a button click, the menu slide out, and feel able to put a lot of things.
References to libraries:
First of all, Drawerlayout this class is in the support library, need to add Android-support-v4.jar this package.

Then import the import android.support.v4.widget.DrawerLayout in front of the program;

If you can't find this class, first update the Android Support Library with the SDK manager, and then on the Android sdk\extras\android\support\ Locate the Android-support-v4.jar under the V4 path, copy the Libs path to the project, and add it to the 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 "> <andro Id.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 "the" the "the", the drawerlayout because it would be drawn Drawer must is on top of it--> <framelayout android:id= "@+id/content_frame" android:layout_width= "Match_parent" android:layout_height= "Match_parent"/> <!--the navigation drawer-->
      W 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:divid 

 erheight= "0DP"/> </android.support.v4.widget.DrawerLayout> </RelativeLayout>

The first child element of Drawerlayout is the primary content, which is the layout that is displayed when the drawer is not open. There was a framelayout, and there was nothing in it.

Drawerlayout's second child element is the contents of the drawer, the drawer layout, which employs a ListView.

Main activity (grilled from official examples):

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.setdrawershadow (R.D

    Rawable.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 has settled in a completely the state. */Public VO ID ondrawerclosed (view view) {Invalidateoptionsmenu ();//creates call to//Onprepa Reoptionsmenu ()}/** called when a drawer has settled into a completely open state.
                      */public void ondraweropened (View drawerview) {invalidateoptionsmenu ();

    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} private void Initlistview () {mdrawerlist = (ListView) findview

    Byid (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.layout.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) {//H  Ighlight 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 has occurred.
  Mdrawertoggle.syncstate (); @Override public void onconfigurationchanged (Configuration newconfig) {super.onconfigurationchanged (newconfi
    g);
  Mdrawertoggle.onconfigurationchanged (Newconfig); @Override public boolean onoptionsitemselected (MenuItem Item) {//Pass the event to Actionbardrawertoggle, I
    F 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);

 }

}

The more tangled is the use of level 11 of an API, so that minsdkversion have limitations, not too low.

Photo Resource The Android website sample is available for download.

After the program is run the effect is as follows:
Before opening the drawer:

After the drawer opens:

Code 2
Today, I looked at the Drawerlayout class and found that there are many ways to use it directly.

Try again, in fact, do not have the above trouble, just define a button to control the 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: paddingbottom= "@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:layout_ Width= "Match_parent" android:layout_height= "Match_parent" > <!--the main content view--> <fram Elayout android:id= "@+id/content_frame" android:layout_width= "match_parent" match _parent "> <button android:id=" @+id/btn android:layout_width= "Match_parent" Android: 
 layout_height= "Wrap_content" android:text= "open"       /> </FrameLayout> <!--the navigation drawer--> <listview android:id= "@+id/l Eft_drawer "android:layout_width=" 240DP "android:layout_height=" match_parent "android:layout_gravity=" St Art "android:background=" #111 "android:choicemode=" Singlechoice "android:divider=" @android: Color/transpa

 Rent "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)
      {
        //Button Press, turn the drawer open
        mdrawerlayout.opendrawer (gravity.left);}}
    )



Using toolbar + Drawerlayout to quickly achieve a high and large menu sideslip
If you have a focus on some applications that follow the latest material design specifications (if not, suppose you have!) , you may find that there are many animations that use the Sideslip menu that looks very comfortable and very tall, as shown in the following example (via reference 2):

Use the official support library today to quickly implement this kind of effect, you need to use toolbar and drawerlayout, detailed steps are as follows: (If you don't know these two widgets, go ahead and Google yourself.)
First you need to add APPCOMPAT-V7 support:

If you created a project on the Android Studio 1.0 RC4, the APPCOMPAT-V7 support has been added by default, and if it is not the latest version, you need to add the following code to Build.gradle:

dependencies {
  ...//other code
  compile ' com.android.support:appcompat-v7:21.0.2 '
}

You need to sync up when you are finished adding gradle

Add Toolbar:

Because toolbar is inherited from view, you can add toolbar directly to the main layout file like other standard controls, but to increase the efficiency of toolbar reuse, you can create a custom_toolbar.xml code in layout as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <android.support.v7.widget.toolbar xmlns:android=
  "http://" Schemas.android.com/apk/res/android "
    xmlns:app=" Http://schemas.android.com/apk/res-auto "
    android:id=" @ +id/tl_custom "
    android:layout_width=" match_parent "
    android:layout_height=" Wrap_content "
    android: Background= "Attr/colorprimary"
    android:minheight= "attr/actionbarsize" android:popuptheme= "
    @style ThemeOverlay.AppCompat.Light "
    app:theme=" @style/themeoverlay.appcompat.actionbar ">
</ Android.support.v7.widget.toolbar>

Description

Android.support.v7.widget.Toolbar-Of course, if you can use Toolbar directly in Lollipop, and you don't need to add v7 support
Xmlns:app-Custom XML named control, in as can be directly specified Res-auto without the need to use the full package name
Both Android:background and android:minheight can be declared in Styles.xml
Add Drawerlayout:

Like toolbar, to improve the efficiency of code reuse, you can create a custom_drawerlayout.xml code in layout as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <android.support.v4.widget.drawerlayout xmlns:android= "http://" Schemas.android.com/apk/res/android "android:id=" @+id/dl_left "android:layout_width=" Match_parent "Android:lay" out_height= "Match_parent" > <!--main layout--> <linearlayout android:layout_width= "Match_parent" Android:la
      yout_height= "Match_parent" > <imageview android:id= "@+id/iv_main" android:layout_width= "100DP" android:layout_height= "100DP"/> </LinearLayout> <!--sideslip menu--> <linearlayout Android:layout_widt H= "Match_parent" android:layout_height= "match_parent" android:background= "#fff" android:layout_gravity= "Start" > <listview android:id= "@+id/lv_left_menu" android:layout_width= "Match_parent" Android:layout_ height= "Match_parent" android:divider= "@null" android:text= "Drawerlayout"/> </LinearLayout> </a Ndroid.support.v4.widget.DrawerLaYout>
 

The Drawerlayout tab has two child nodes, one is the left menu, one is the main layout, in addition to the left menu starting position set to android:layout_gravity= "Start"

Implement Activity_main.xml:

<linearlayout 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:orientation= "vertical"
  tools:context= ". Mainactivity ">
    <!--toolbar-->
    <include layout=" @layout/custom_toolbar "/>
    <!-- drawerlayout-->
    <include layout= "@layout/custom_drawerlayout"/>
</LinearLayout>

Direct use of include tags, simple and straightforward

Perfect Java code:

public class Mainactivity extends Actionbaractivity {//Declare related variables private Toolbar Toolbar;
  Private Drawerlayout mdrawerlayout;
  Private Actionbardrawertoggle Mdrawertoggle;
  Private ListView Lvleftmenu;
  Private string[] LVs = {"List item", "List item", "List item", "List item 04"};
  Private Arrayadapter Arrayadapter;
  Private ImageView Ivrunningman;
  Private Animationdrawable manimationdrawable;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main); Findviews ();
    Get control//Jingdong Runningman animation effect, and this time toolbar independent manimationdrawable = (animationdrawable) ivrunningman.getbackground ();
    Manimationdrawable.start (); Toolbar.settitle ("toolbar");/Set toolbar heading Toolbar.settitletextcolor (Color.parsecolor ("#ffffff");
    Sets the title Color Setsupportactionbar (toolbar); Getsupportactionbar (). Sethomebuttonenabled (True); The set return key can be Getsupportactionbar (). setdisplayhomeasupenableD (TRUE); Create a return key and implement toggle/close listener Mdrawertoggle = new Actionbardrawertoggle (this, Mdrawerlayout, toolbar, R.string.open, R.string.clo
        SE) {@Override public void ondraweropened (View drawerview) {super.ondraweropened (Drawerview);
      Manimationdrawable.stop ();
        @Override public void ondrawerclosed (View drawerview) {super.ondrawerclosed (Drawerview);
      Manimationdrawable.start ();
    }
    };
    Mdrawertoggle.syncstate ();
    Mdrawerlayout.setdrawerlistener (Mdrawertoggle); Set Menu List arrayadapter = new Arrayadapter (this, Android.
    R.layout.simple_list_item_1, LVS);
  Lvleftmenu.setadapter (Arrayadapter);
    private void Findviews () {Ivrunningman = (ImageView) Findviewbyid (R.id.iv_main);
    toolbar = (toolbar) Findviewbyid (R.id.tl_custom);
    Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.dl_left);
  Lvleftmenu = (ListView) Findviewbyid (R.id.lv_left_menu);
 }
}

The

is of course more important and styles.xml and Colors.xml, as follows: 

 <resources> <style name= "Apptheme" Theme.AppCompat.Light.NoActionBar "> <!--status bar color--> <item name=" Colorprimarydark "> @color/indigo_color primarydark</item> <!--toolbar color--> <item name= "colorprimary" > @color/indigo_colorprimary</it Em> <!--return key style--> <item name= "Drawerarrowstyle" > @style/apptheme.drawerarrowtoggle</item> & lt;/style> <style name= "Apptheme.drawerarrowtoggle" parent= "Base.Widget.AppCompat.DrawerArrowToggle" > Item Name= "COLOR" > @android:color/white</item> </style> </resources> <?xml version= "1.0" encoding= "Utf-8"?> <resources> <color name= "Indigo_colorprimarydark" > #303f9f </color> < Color name= "Indigo_colorprimary" > #3f51b5 </color> <color name= "Indigo_nav_color" > #4675FF </color > </resources> 

To achieve a large menu sideslip, the final effect is as follows (note: On the Yosemite seemingly direct record phone screen does not appear to work, and animation due to the frame rate reason can not be real time, the first look like this ~)

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.