Detailed explanation of drawerlayout usage of Android sideslip menu


In the early days of onconfigurationchanged, the function of sideslip menu was implemented mostly through a dependency package called slidingmenu on GitHub. Later, Google added drawerlayout to the V4 package to realize this function, which can completely replace slidingmenu. Here we will learn how to use drawerlayout

1) Create drawerlayout

1) In the layout file, the layout is set to drawerlaout. Because it is a function of V4 package, the full package name must be written. Note that the first thing is to write the main view layout first, and then the view in the drawer. Here we put the listview into the drawer

<pre name="code"><
  <! -- the main content view when the drawer is closed -- >
  <! -- the Navigation view left side opened Navigation view -- >
    Android: layout_gravity = "start" // slide out the menu from left to right. If end is selected, the menu will slide out from right to left

2) Load the drawerlayout in activity, and adapt the data to the list in the drawer, so that the drawer layout is loaded in.

public class MainActivity extends Activity implements OnItemClickListener{
 private DrawerLayout mDrawerLayout;
 private ListView mListView;
 Private ArrayList < string > menulist; // data
 Private arrayadapter < string > adapter; // adapter
// private ActionBarDrawerToggle mDrawerToggle;
// private String mTitle;
 protected void onCreate(Bundle savedInstanceState) {
 // mTitle=(String) getTitle();
 mDrawerLayout=(DrawerLayout) findViewById(;
 mListView=(ListView) findViewById(;
 menuList=new ArrayList<String>();
 for(int i=0;i<5;i++)
  Menulist. Add ("Liu Jiawei" + I);
 adapter=new ArrayAdapter<String>(this,

2) Add click event to the list in the drawer, and dynamically add fragments to enter the main view

1) Add a click event to the list item in the drawer. For each click on the list item, let it add a fragment in the main content view to display the content in the clicked list item. Write the layout in the fragment layout first, and let it display a piece of text here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
  android:orientation="vertical" >

2) Create fragment, rewrite oncreateview() here, load the layout, and then get the content of the click item. This is achieved in mainactivity by letting the fragment carry parameters

package com.example.drawerlayout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ContentFragment extends Fragment {
 private TextView tv;
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View view=inflater.inflate(R.layout.fragment_content,container,false);
 tv=(TextView) view.findViewById(;
 String text = getarguments(). GetString ("text"); // get the passed in value
 return view;

3) Add a click event to the list in the drawer. Click to enter the fragment interface. The fragment carries the parameter of bundle type. The value of the parameter is passed in the list data menulist.get (position), The method of using fragments is as follows: after getting the instance of fragments, get the fragment manager through getfragmentmanager(), open the transaction to the fragment manager, and then the fragment manager after opening the transaction replaces the original layout of the main view with the method of replace(), so that a fragment is added

Finally, don’t forget to close the drawer

 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 //Dynamically insert a fragment in FrameLayout
      Fragment contentfragment = new contentfragment(); // create fragment instance
      Bundle args = new bundle(); // let each fragment carry parameters and initialize to bundle type
      Args. Putstring ("text", menulist. Get (position)); // parameter put enters the value of string type and passes in the value of the currently clicked menu item
      Contentfragment. Setarguments (args); // let the fragment carry the parameters
      FragmentManager fm=getFragmentManager(); 
      FM. Begintransaction(). Replace (, contentfragment). Commit(); // start the transaction, add fragments to the container, and finally commit the transaction
    Mdrawerlayout.closedrawer (mlistview); // close the contents of the drawer when entering the fragment interface

3) Monitor drawer opening and closing events

Using actionbardrawertoggle, it was originally in the V4 package. Now Google has moved it to the V7 package, so we need to introduce the V7 dependency package

When introducing the V7 package, I encountered an error,support\v7\appcompat\res\values-21\themes-base.xml:error:Error retrieving parent for item :No resources found that matches the given name.This is because the version of V7 package is too low. The solution is to change target = android-8 to more than 21 in project: properties

When the drawer is open, the title bar changes to “please select”. When the drawer is closed, the title bar changes to the original app title

mTitle=(String) getTitle()

mDrawerToggle=new ActionBarDrawerToggle(this, mDrawerLayout,
  public void onDrawerOpened(View drawerView) {
  Getactionbar(). Settitle ("please select");
  Invalidateoptionsmenu(); // redraw the menu item on actionbar, and call onpreareoptionsmenu() when executing this method
  public void onDrawerClosed(View drawerView) {

Because we have changed the content of the actionbar, calling invalideoptionsmenu() will redraw the menu items on the actionbar. When executing this method, it will call onpreareoptionsmenu(), so we can perform some operations here by judging whether the drawer is open or closed, such as hiding the menu items of the actionbar.

Since we want to hide it, the premise is that we need to have menu items. Here, we need to add a search button to the actionbar. The way to add a button to the actionbar has been mentioned in the blog about the actionbar, so we can directly operate here


<menu xmlns:android=""
tools:context="com.example.drawerlayout.MainActivity" >

Then load the menu in

 public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(, menu);
 return super.onCreateOptionsMenu(menu);

Set the click event for this search button along the way

/*Set click event for websearch of actionbar*/
 public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
  Intent intent=new Intent();
 return super.onOptionsItemSelected(item);

Finally, in onprepareoptionsmenu(), judge by drawing layout’s isopen(). If it is opened, the menu item will be hidden

 public boolean onPrepareOptionsMenu(Menu menu) {
  /*Here, judge whether to display the websearch icon of actionbar by judging whether drawerlayout is on or off*/
 boolean isDrawerOpen=mDrawerLayout.isDrawerOpen(mListView);
 Menu. Finditem ( Setvisible (! Isdraweropen); // if drawerlayout is closed, websearch in actionbar will be displayed
 return super.onPrepareOptionsMenu(menu);

4) Click the icon to open and close the drawer

In order to use the drawer more conveniently, we can click the icon to open and close the drawer interface

1) Open the app icon function in oncreate()

//Enable the app icon function of actionbar

2) Because the icon is also a menu item, clicking it will also call onoptionsiteselected (MenuItem item)

 public boolean onOptionsItemSelected(MenuItem item) {
 //Combine the icon on the actionbar with the drawer
  return true;

This function is implemented, but the icon is still the original icon. Now synchronize the drawer layout with actionbardrawertoggle

3) Google officially recommends syncing in onpostcreate(), and Google recommends writing onconfigurationchanged()

 protected void onPostCreate(Bundle savedInstanceState) {
 //Synchronize actionbardrawertoggle with drawerlayout
 //Set the drawer icon in actionbardrawertoggle to the icon of home button in actionbar
  //This method is used to monitor the change of mobile phone status, such as horizontal screen and vertical screen switching
 public void onConfigurationChanged(Configuration newConfig) {

Combining all the above, the renderings are as follows


The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer. If you want to know more about it, please check the relevant links below