Android------drawerlayout for drawer effect

Source: Internet
Author: User

How do I achieve the drawer effect in Android?

1. Creating an XML file

Its root view is <android.support.v4.widget.DrawerLayout/>

This XML is divided into two parts, a view of the main content, and a view of the drawer in part.

The main content view is generally framelayout, and must be the first view of the drawerlayout, and its height matches the height of the parent view.

The drawer view is generally a ListView, which should be noted when writing a drawer view

1. Width generally less than 320DP

The 2.android:layout_gravity property is the position of the drawer

When the property is Left/start, it is on the left

When the property is Right/end, it is on the right

Recommended use of Start/end

3.android:choicemode = "Singlechoice"

4.android:divider and Android:dividerheight

<android.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 ">    <framelayout        android:id=" @+id/content_frame "        android:layout_width=" Match_parent "        android:layout_height= "Match_parent" >    </FrameLayout>    <listview        android:id= "@+id/ Left_drawer "        android:layout_width=" 240DP "        android:layout_height=" match_parent "        android:layout_ gravity= "Start"        android:choicemode= "Singlechoice"        android:background= "#ffffcc"        android:divider= "@android: Color/transparent"        android:dividerheight= "0DP" >    </listview></ Android.support.v4.widget.drawerlayout>


By deploying this XML file to the emulator, you can see a simple effect:

2. Add content to the drawer:

Because the drawer view is a ListView, so use the adapter

Declare the various components and the list,adapter used in the activity

public class Mainactivity extends Activity {private drawerlayout mdrawerlayout;private ListView mdrawerlist;private Arraylist<string> mlist;private arrayadapter<string> adapter; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mDrawerLayout = ( Drawerlayout) Findviewbyid (r.id.drawer_layout); mdrawerlist = (ListView) Findviewbyid (r.id.left_drawer);// Initialize mlistmlist = new arraylist<string> (), for (int i = 0; i < 5; i++) {mlist.add ("Item--->" + (i + 1));} Initialize the adapter//adapter data to fill adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1, mlist); Mdrawerlist.setadapter (adapter);}}


3. Monitor the left side of the ListView

Now click on the left drawer bar does not have any effect, need to set the listener for the left Liseview (Onitemclicklistener) and implement the Onitemclick method

When you click on the menu item in the left drawer, a fragment is inserted dynamically in the right view.

You need to create a new class content_fragment inherit fragment, and override the Oncreateview method to return the view generated by the Inflater.inflate method

public class Content_fragment extends fragment {private TextView TextView; @Overridepublic View Oncreateview ( Layoutinflater Inflater, ViewGroup container,bundle savedinstancestate) {//Inflater.inflate (resource, Root, Attachtoroot) View view = Inflater.inflate (R.layout.fragment_content, container,false); TextView = (TextView) View.findviewbyid (R.id.textview);//receives the passed arguments and displays the string text = Getarguments () in TextView. GetString ("text"); Textview.settext (text); return view;}}


Inflater.inflate (Resource, root, Attachtoroot)

Inflate 's role is simply to Find out a layout of the XML definition

Parameter 1: Load Error thrown inflateexception to load XML resource file

Parameter 2: Parent layer of the new view

If the third argument is attachtoroot true, The root is returned as the root object, or the root is simply the layoutparams property of the object is appended to the root layout object of the resource object, which is the layout file the outermost View of A resource, such as a linearlayout or other Layout object.

When you click on a menu item in the left drawer, you need to pass the data to the fragment that will be populated into the fragmentlayout, through the Fragment Setarguments (Bundle) method.

The new fragment calls the Getarguments.getxx () method to get the data passed in.

Set Listener Mdrawerlist.setonitemclicklistener (this), @Overridepublic void Onitemclick (adapterview<?> parent, View view, int Position,long ID) {//dynamically insert a fragment to the right fragment contentfragment = new Content_fragment (); Bundle bundle = new bundle (); Bundle.putstring ("Text", Mlist.get (position));//Pass Data contentfragment.setarguments ( bundle); Fragmentmanager fm = Getfragmentmanager (); fm.begintransaction ()//Open a transaction. replace (R.id.content_frame, contentfragment)//New view replaces the original view and fills the contentfragment to the right. commit (); When you click on a menu item in the left drawer, the view jumps to the right to display the contentfragment, At this time, the left drawer needs to hide the Mdrawerlayout.closedrawer (mdrawerlist);}


When running in the simulator, clicking on a menu item on the left will display the corresponding view on the right.

Click the item--->3

4. Open and close the monitor drawer

Set the listener for Drawerlayout and the title of the top will change when the drawer is open/closed.

There are usually two ways to set up listening:

1.drawerlayout.setdrawerlistener (Drawerlayout.drawerlistener)

2. If the activity contains Actionbar, you can use the Actionbardrawertoggle class directly, which is a subclass of Drawerlistener

A) Change Android. R.id.home icon

b) Drawer with animation (Syncstate ()) when pulling or hiding

c) can listen drawer pull out, hide events

Overwrite Actionbardrawertoggle ondraweropened () and ondrawerclosed () to pull out or hide in the listening drawer

Onpostcreate and Onconfigurationchanged methods for covering activity when using Actionbardrawertoggle

 

public class Mainactivity extends Activity implements Onitemclicklistener {private Drawerlayout mdrawerlayout;private ListView mdrawerlist;private arraylist<string> mlist;private arrayadapter<string> adapter;private Actionbardrawertoggle mdrawertoggle;private String mtitle, @Overrideprotected void OnCreate (Bundle savedinstancestate {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mtitle = (String) getTitle (); Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); mdrawerlist = (ListView) Findviewbyid (R.id.left_ drawer);//Initialize mlistmlist = new arraylist<string> (); for (int i = 0; i < 5; i++) {mlist.add ("Item--->" + (i + 1) );} Initialize the adapter//adapter data to fill adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1, mlist); Mdrawerlist.setadapter (adapter);//Set Listener Mdrawerlist.setonitemclicklistener ( This): Mdrawertoggle = new Actionbardrawertoggle (this, mdrawerlayout,r.drawable.ic_drawer,//Apply the icon in the upper left corner r.string.drawer _open, R.String.drawer_close) {//overwrite drawer open/Close method @overridepublic void ondraweropened (View drawerview) {super.ondraweropened ( Drawerview);//When the drawer is open, the top displays the title Getactionbar (). Settitle ("Please select"); @Overridepublic void ondrawerclosed (View drawerview) {super.ondrawerclosed (Drawerview);//When the drawer is closed, The caption displayed is Getactionbar (). Settitle (mtitle);}; Mdrawerlayout.setdrawerlistener (Mdrawertoggle);} @Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long ID) {// Dynamically inserting a fragment to the right fragment contentfragment = new Content_fragment (); Bundle bundle = new bundle (); Bundle.putstring ("Text", Mlist.get (position));//Pass Data contentfragment.setarguments ( bundle); Fragmentmanager fm = Getfragmentmanager (); fm.begintransaction ()//Open a transaction. replace (R.id.content_frame, contentfragment)//New view replaces the original view and fills the contentfragment to the right. commit (); When you click on a menu item in the left drawer, the view jumps to the right to display the contentfragment, At this time, the left drawer needs to hide the Mdrawerlayout.closedrawer (mdrawerlist);}}


5. Add an icon in the upper right corner , which is actually optionmenu

Modify Main.xml

<menu xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http://schemas.android.com /tools "    tools:context=" com.example.drawerlayoutbymyself.MainActivity ">    <item        android:id=" @+ Id/action_websearch "        android:icon=" @drawable/web_search "        android:showasaction=" Ifroom|withtext        " Android:title= "Websearch"/></menu>


You need to redraw the menu item when the drawer is open or hidden, you need to have a Oncreateoptionsmenu method

@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}


Adding the Invalidateoptionsmenu () method to the Mdrawertoggle listener event

When the method is called, the system automatically calls the Onprepareoptionsmenu method and needs to override the method

@Overridepublic boolean Onprepareoptionsmenu (Menu menu) {//Drawer is open Boolean isdraweropen = Mdrawerlayout.isdraweropen ( mdrawerlist); Menu.finditem (R.id.action_websearch) setvisible (!isdraweropen); return Super.onprepareoptionsmenu ( menu);}


At this point, when the drawer is open or hidden, the icon in the upper right corner of the screen changes accordingly. However, clicking on this icon does not have any response. Need to overwrite onoptionsitemselected method

@Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.action_websearch:i Ntent Intent = new Intent (); Intent.setaction ("Android.intent.action.VIEW"); Uri uri = uri.parse ("http://www.baidu.com"); Intent.setdata (URI); startactivity (intent); break;default:break;} return super.onoptionsitemselected (item);}


When you click on the icon in the upper right corner, the browser will be called to open the Baidu homepage.

Full code:

public class Mainactivity extends Activity implements Onitemclicklistener {private Drawerlayout mdrawerlayout;private ListView mdrawerlist;private arraylist<string> mlist;private arrayadapter<string> adapter;private Actionbardrawertoggle mdrawertoggle;private String mtitle, @Overrideprotected void OnCreate (Bundle savedinstancestate {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mtitle = (String) getTitle (); Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); mdrawerlist = (ListView) Findviewbyid (R.id.left_ drawer);//Initialize mlistmlist = new arraylist<string> (); for (int i = 0; i < 5; i++) {mlist.add ("Item--->" + (i + 1) );} Initialize the adapter//adapter data to fill adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1, mlist); Mdrawerlist.setadapter (adapter);//Set Listener Mdrawerlist.setonitemclicklistener ( This): Mdrawertoggle = new Actionbardrawertoggle (this, mdrawerlayout,r.drawable.ic_drawer,//Apply the icon in the upper left corner r.string.drawer _open, R.String.drawer_close) {//overwrite drawer open/Close method @overridepublic void ondraweropened (View drawerview) {super.ondraweropened ( Drawerview)/////When the drawer is open, the top display title Getactionbar (). Settitle ("select");//Redraw the menu item, automatically call Onprepareoptionsmenu (), To override the method Invalidateoptionsmenu ();} @Overridepublic void ondrawerclosed (View drawerview) {super.ondrawerclosed (Drawerview);//When the drawer is closed, The caption displayed is Getactionbar (). Settitle (Mtitle);//Redraw menu item Invalidateoptionsmenu ();}}; Mdrawerlayout.setdrawerlistener (Mdrawertoggle);} @Overridepublic boolean Onprepareoptionsmenu (Menu menu) {//Drawer is open Boolean isdraweropen = Mdrawerlayout.isdraweropen ( mdrawerlist); Menu.finditem (R.id.action_websearch) setvisible (!isdraweropen); return Super.onprepareoptionsmenu ( menu);} @Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long ID) {// Dynamically inserting a fragment to the right fragment contentfragment = new Content_fragment (); Bundle bundle = new bundle (); Bundle.putstring ("Text", Mlist.get (position));//Pass Data contentfragment.setarguments ( bundle); Fragmentmanager fm = Getfragmentmanager (); fm.begintransaction ()//Open a transaction. replace (R.id.content_frame, contentfragment)// The new view replaces the original view and fills the contentfragment to the right. commit (); When you click on a menu item in the left drawer, the view jumps to the right to display the contentfragment, The left drawer needs to hide the Mdrawerlayout.closedrawer (mdrawerlist);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.action_websearch:i Ntent Intent = new Intent (); Intent.setaction ("Android.intent.action.VIEW"); Uri uri = uri.parse ("http://www.baidu.com"); Intent.setdata (URI); startactivity (intent); break;default:break;} return super.onoptionsitemselected (item);}}


6. Add an icon in the upper left corner to open the drawer when the user taps the icon

Add code in Mainactivity's OnCreate method:

Turn on Actionbar app icon function Getactionbar (). Setdisplayhomeasupenabled (True); Getactionbar (). Sethomebuttonenabled (True );


This time if you deploy to the emulator, you will find a return icon in the upper left corner, but the click does not have any effect

Combine the icon on the Actionbar with the drawer if (mdrawertoggle.onoptionsitemselected (item)) {return true;}


Add a judge to the Onoptionsitemselected method, and the icon in the upper-left corner is also a menu item

Click on the icon in the top left corner to open the drawer, and the top left corner icon will also animate

Final Activity code:

public class Mainactivity extends Activity implements Onitemclicklistener {private Drawerlayout mdrawerlayout;private ListView mdrawerlist;private arraylist<string> mlist;private arrayadapter<string> adapter;private Actionbardrawertoggle mdrawertoggle;private String mtitle, @Overrideprotected void OnCreate (Bundle savedinstancestate {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); mtitle = (String) getTitle (); Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); mdrawerlist = (ListView) Findviewbyid (R.id.left_ drawer);//Initialize mlistmlist = new arraylist<string> (); for (int i = 0; i < 5; i++) {mlist.add ("Item--->" + (i + 1) );} Initialize the adapter//adapter data to fill adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1, mlist); Mdrawerlist.setadapter (adapter);//Set Listener Mdrawerlist.setonitemclicklistener ( This): Mdrawertoggle = new Actionbardrawertoggle (this, mdrawerlayout,r.drawable.ic_drawer,//Apply the icon in the upper left corner r.string.drawer _open, R.String.drawer_close) {//overwrite drawer open/Close method @overridepublic void ondraweropened (View drawerview) {super.ondraweropened ( Drawerview)/////When the drawer is open, the top display title Getactionbar (). Settitle ("select");//Redraw the menu item, automatically call Onprepareoptionsmenu (), To override the method Invalidateoptionsmenu ();} @Overridepublic void ondrawerclosed (View drawerview) {super.ondrawerclosed (Drawerview);//When the drawer is closed, The caption displayed is Getactionbar (). Settitle (Mtitle);//Redraw menu item Invalidateoptionsmenu ();}}; Mdrawerlayout.setdrawerlistener (Mdrawertoggle);//Open Actionbar on the app icon function Getactionbar (). setdisplayhomeasupenabled (true); Getactionbar (). Sethomebuttonenabled (true);} @Overridepublic boolean Onprepareoptionsmenu (Menu menu) {//Drawer is open Boolean isdraweropen = Mdrawerlayout.isdraweropen ( mdrawerlist); Menu.finditem (R.id.action_websearch) setvisible (!isdraweropen); return Super.onprepareoptionsmenu ( menu);} @Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long ID) {// Dynamically inserting a fragment to the right fragment contentfragment = new Content_fragment (); Bundle bundle = NewBundle (); Bundle.putstring ("Text", Mlist.get (position));//Transmit Data contentfragment.setarguments (bundle); Fragmentmanager fm = Getfragmentmanager (); fm.begintransaction ()//Open a transaction. replace (R.id.content_frame, contentfragment)//New view replaces the original view and fills the contentfragment to the right. commit (); When you click on a menu item in the left drawer, the view jumps to the right to display the contentfragment, At this time, the left drawer needs to hide the Mdrawerlayout.closedrawer (mdrawerlist);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//combines the icon on the Actionbar with the drawer if ( Mdrawertoggle.onoptionsitemselected (item)) {return true;} Switch (Item.getitemid ()) {case R.id.action_websearch:intent Intent = new Intent (); Intent.setaction (" Android.intent.action.VIEW "); Uri uri = uri.parse ("http://www.baidu.com"); Intent.setdata (URI); startactivity (intent); break;default:break;} return super.onoptionsitemselected (item);} @Overrideprotected void Onpostcreate (Bundle savedinstancestate) {super.onpostcreate (savedinstancestate)///need to synchronize actiondrawertoggle with Drawerlayout//drawer icon in Actionbardrawertoggle, set to Home-button Iconmdrawertoggle.syncstate ();} @Overridepublic void onconfigurationchanged (Configuration newconfig) {super.onconfigurationchanged (newconfig); Mdrawertoggle.onconfigurationchanged (Newconfig);}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android------drawerlayout for 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.