preface

DrawerLayout is the Support Library package to achieve the effect of the slide menu control, it can be said that DrawerLayout is the third party control such as MenuDrawer after the emergence of the product, Google reference and appeared. DrawerLayout is divided into two parts: side menu and main content area. The side menu can be expanded and hidden according to gestures (DrawerLayout itself features), and the content of the main content area can be changed with the click of the menu.


DrawerLayout basic use

DrawerLayout is actually a layout control, inherit ViewGroup, and LinearLayout and other controls is a kind of thing, belongs to the same control. But DrawerLayout has the ability to slide. As long as you write the layout according to DrawerLayout, you can have the effect of sideslipping.

The simplest way to use DrawerLayout is to add two sub-layouts, respectively representing the main page of the APP and the side slide menu page.


      
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/drawerLayout"  android:layout_width="match_parent"  android:layout_height="match_parent">  <! -- Home page -->  <ImageView  android:layout_width="match_parent"  android:layout_height="match_parent"  android:scaleType="centerCrop"  android:src="@mipmap/meizi_2" />  <! -- Scroll menu page -->  <ImageView  android:layout_width="match_parent"  android:layout_height="match_parent"  android:scaleType="centerCrop"  android:src="@mipmap/pangzi" /> </androidx.drawerlayout.widget.DrawerLayout> Copy the code

Complete the above layout file to achieve the following effect:


Two, DrawerLayout + ToolBar use

In daily development, each interface will have a ToolBar, and the content that slides out will be at the bottom of the ToolBar. The most common is a small Icon on the left side of the ToolBar (known as the triple bar) that loads an animation to turn into a return button when the sidebar menu is displayed. You don’t need to add an Icon to the ToolBar, just use the ActionBarDrawerToggle class to do this.

ActionBarDrawerToggle is a “three” and click change “←”

What ActionBarDrawerToggle does:

  1. Change the android.r.D. home return icon
  2. DrawerLayout pulls out and hides with Android.R.IDA Home animation effect
  3. Listen for DrawerLayout to pull out and hide

To implement the slide menu at the bottom of the ToolBar, modify the XML file and place the ToolBar outside the DrawerLayout.


      
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical">   <androidx.appcompat.widget.Toolbar  android:id="@+id/toolbar"  android:layout_width="match_parent"  android:layout_height="? attr/actionBarSize"  android:background="? attr/colorPrimary"  app:layout_scrollFlags="scroll|enterAlways"  app:title="DrawerLayout"  tools:ignore="MissingConstraints" />   <androidx.drawerlayout.widget.DrawerLayout  android:id="@+id/drawerLayout"  android:layout_width="match_parent"  android:layout_height="match_parent">   <ImageView  android:layout_width="match_parent"  android:layout_height="match_parent"  android:scaleType="centerCrop"  android:src="@mipmap/meizi_2" />   <ImageView  android:layout_width="match_parent"  android:layout_height="match_parent"  android:scaleType="centerCrop"  android:src="@mipmap/pangzi" />   </androidx.drawerlayout.widget.DrawerLayout> </LinearLayout> Copy the code
// Set the effect of the icon [" three "-- "←"] in the upper left corner
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
actionBarDrawerToggle.syncState();
drawerLayout.addDrawerListener(actionBarDrawerToggle);
Copy the code

NavigationView introduction

NavigationView is a specification of Google’s Material Design for sideslipping, so a new space is proposed to standardize the basic style of the sideslipping menu.

For drawer menu interface many apps have applications, before writing drawer interface need to be customized. Now Google provides NavigationView + DrawerLayout combined to provide a good side-scrolling interactive experience.

NavigationView common methods

methods introduce
addHeaderView(View view) Add the view as the title of the navigation menu
getHeaderCount() Gets the number of headers in this NavigationView
getHeaderView(int index) Gets the title view for the specified location
getMenu() Returns the instance of Menu associated with this navigation view
inflateMenu(int resId) Add menu resources in this navigation view
removeHeaderView(View view) Delete the title view you added earlier
setItemBackgroundResource(int resId) Sets the background of the menu item to the given resource
setItemIconSize(int iconSize) Sets the size, in pixels, of ICONS used for menu items
setItemTextAppearance(int resId) Sets the text appearance of the menu item to the given resource
setItemTextColor(ColorStateList textColor) Sets the text color to use on the menu item
setItemIconTintList(ColorStateList tint) Sets the color of the Icon used on the menu item
     setNavigationItemSelectedListener(NavigationView listener)      Sets a listener that will be notified when a menu choice is selected

NavigationView basic use

DrawerLayout + NavigationView + ToolBar is the most common effect in a project and usually has two effects:

  • The scroll menu is at the bottom of the ToolBar

  • Slide menu immersive overlay ToolBar display

The first effect is actually to place the ToolBar layout outside of DrawerLayout in the XML layout, and the second effect is to place the ToolBar inside of DrawerLayout’s internal home page layout, and then achieve an immersive effect. This article source code has an immersive implementation of the tool class, interested friends can download the source reference.

XML layout file


      
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/drawerLayout"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:fitsSystemWindows="true">   <LinearLayout  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical">   <androidx.appcompat.widget.Toolbar  android:id="@+id/toolbar"  android:layout_width="match_parent"  android:layout_height="? attr/actionBarSize"  android:background="? attr/colorPrimary"  app:layout_scrollFlags="scroll|enterAlways"  app:title="DrawerLayout"  app:titleTextColor="#FFF"  tools:ignore="MissingConstraints" />   <ImageView  android:layout_width="match_parent"  android:layout_height="match_parent"  android:scaleType="centerCrop"  android:src="@mipmap/meizi_2" />   </LinearLayout>   <com.google.android.material.navigation.NavigationView  android:id="@+id/navigationView"  android:layout_width="wrap_content"  android:layout_height="match_parent"  android:layout_gravity="start"  app:headerLayout="@layout/nav_header_main"  app:insetForeground="@android:color/transparent"  app:menu="@menu/activity_main_drawer" />  </androidx.drawerlayout.widget.DrawerLayout> Copy the code

NavigationView is a DrawerLayout control that introduces two properties:

  • App: insetForeground = “@ android: color/transparent” NavigationView immersive display

  • App :headerLayout=”@layout/nav_header_main” Add a Header layout to NavigationView

  • App :menu=”@menu/activity_main_drawer” NavigationView Adds the tag Item to the menu

2, HeaderLayout layout file


      
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
 android:layout_height="200dp"  android:background="? attr/colorPrimary"  android:gravity="bottom"  android:theme="@style/ThemeOverlay.AppCompat.Dark">   <com.caobo.slideviewdemo.drawerlayout.MovingImageView  android:id="@+id/movingImageView"  android:layout_width="match_parent"  android:layout_height="250dp"  android:scaleType="centerCrop"  android:src="@mipmap/menu_header_background"  app:miv_load_on_create="false"  app:miv_max_relative_size="3.0"  app:miv_min_relative_offset="0.2"  app:miv_repetitions="1"  app:miv_speed="100"  app:miv_start_delay="100" />   <de.hdodenhof.circleimageview.CircleImageView  android:layout_width="100dp"  android:layout_height="100dp"  android:layout_marginLeft="16dp"  android:layout_marginTop="30dp"  android:paddingTop="16dp"  android:src="@mipmap/header_icon"  app:civ_border_color="@color/colorWhite"  app:civ_border_width="2dp" />   <TextView  android:id="@+id/tv_nick"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:layout_gravity="bottom"  android:layout_marginLeft="16dp"  android:layout_marginTop="10dp"  android:layout_marginBottom="16dp"  android:paddingLeft="5dp"  android:text="Learn and live."  android:textAppearance="@style/TextAppearance.AppCompat.Body1"  android:textSize="18sp" /> </FrameLayout>  Copy the code

Menu file

The ICONS here are all displayed using vector images. If you do not already know how to use vector images, please refer to:

The Android Material Design Icon Genenerator plugin provides a complete set of Icon ICONS for individual developers


      
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
 android:id="@+id/group_item_github"  android:icon="@drawable/ic_vector_github_grey"  android:title="Project Homepage" />  <item  android:id="@+id/group_item_more"  android:icon="@drawable/ic_vector_more"  android:title="More content" />  <item  android:id="@+id/group_item_qr_code"  android:icon="@drawable/ic_vector_qr_code"  android:title="Two-dimensional code" />  <item  android:id="@+id/group_item_share_project"  android:icon="@drawable/ic_vector_share"  android:title="Share projects" />  </group>  <item android:title="Options">  <menu>  <item  android:id="@+id/item_model"  android:icon="@drawable/ic_vetor_setting"  android:title="Night mode" />  <item  android:id="@+id/item_about"  android:icon="@drawable/ic_vector_about"  android:title="About" />  </menu>  </item> </menu>  Copy the code

4, Activity code implementation

NavigationView is basically done in XML files, so there is no need to do much processing in the Activity, just need to add the Menu listener in the Activity. This project uses a drawing ImageView, so after the side slide menu, the bottom picture will have an animation effect, interested in the bottom can download the source code to learn.

public class DrawerLayoutActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.drawerLayout)
 DrawerLayout drawerLayout;  @BindView(R.id.navigationView)  NavigationView navigationView;  MovingImageView movingImageView;  private ActionBarDrawerToggle actionBarDrawerToggle;   @Override  protected void initView(a) {  movingImageView = navigationView.getHeaderView(0).findViewById(R.id.movingImageView);  // Set the effect of the icon [" three "-- "←"] in the upper left corner  actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);  actionBarDrawerToggle.syncState();  drawerLayout.addDrawerListener(actionBarDrawerToggle);   // Set NavigationMenuView not to scroll  NavigationMenuView navigationMenuView = (NavigationMenuView) navigationView.getChildAt(0);  if(navigationMenuView ! =null) {  navigationMenuView.setVerticalScrollBarEnabled(false);  }  / / NavigationView listening in  navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {  @Override  public boolean onNavigationItemSelected(@NonNull MenuItem item) {  switch (item.getItemId()) {  case R.id.group_item_github:  Toast.makeText(DrawerLayoutActivity.this."Project Homepage",Toast.LENGTH_SHORT).show();  break;  case R.id.group_item_more:  Toast.makeText(DrawerLayoutActivity.this."More content",Toast.LENGTH_SHORT).show();  break;  case R.id.group_item_qr_code:  Toast.makeText(DrawerLayoutActivity.this."Two-dimensional code",Toast.LENGTH_SHORT).show();  break;  case R.id.group_item_share_project:  Toast.makeText(DrawerLayoutActivity.this."Share projects",Toast.LENGTH_SHORT).show();  break;  case R.id.item_model:  Toast.makeText(DrawerLayoutActivity.this."Night mode",Toast.LENGTH_SHORT).show();  break;  case R.id.item_about:  Toast.makeText(DrawerLayoutActivity.this."About",Toast.LENGTH_SHORT).show();  break;  }  item.setCheckable(false);  drawerLayout.closeDrawer(GravityCompat.START);  return true;  }  });  }   @Override  protected int getLayoutResID(a) {  return R.layout.activity_drawerlayout;  } } Copy the code

NavigationView full screen effect

1. Set full-screen display

NavigationView set Android :layout_width=”match_parent”

ViewGroup.LayoutParams mLayoutParams = navigationView.getLayoutParams();
int width = getResources().getDisplayMetrics().widthPixels;
mLayoutParams.width = width;
navigationView.setLayoutParams(mLayoutParams);
Copy the code

2, imitation QQ side slide menu effect

According to NavigationView full screen effect, imitate QQ personal center slide menu effect, in fact, we found QQ so awesome software, is also the use of Google native controls to achieve, you can imagine the Material Design series of powerful controls. The QQ sideslip menu is composed of the following two points:

  1. QQ side slide menu spread full screen
  2. The home page slides along with the menu

First of all we have to realize, only the above four lines of code you can set the NavigationView full screen effect, and then just need to the main page sliding effect can be achieved with the menu, we remember previously DrawerLayout. AddDrawerListener () method, You can listen for events with four callback methods:

  • OnDrawerSlide (View drawerView, float slideOffset) called when the position of the drawer changes

  • OnDrawerOpened (View drawerView) The side slide interface is triggered

  • OnDrawerClosed (View drawerView) Disables the side slide interface

  • Triggered when onDrawerStateChanged(int newState) status changes

To achieve QQ effect, onDrawerSlide(View drawerView, float slideOffset) returns the offset from hidden to open drawer menu. Value 0~1, drawerView is the side menu layout, the specific implementation code is as follows:


      
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
 android:layout_width="match_parent"  android:layout_height="match_parent">   <ImageView  android:layout_width="match_parent"  android:layout_height="match_parent"  android:scaleType="centerCrop"  android:src="@mipmap/qq_1" />   <com.google.android.material.navigation.NavigationView  android:id="@+id/navigationView"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_gravity="start"  app:headerLayout="@layout/nav_header_main"  app:insetForeground="@android:color/transparent"  app:menu="@menu/activity_main_drawer" />  </androidx.drawerlayout.widget.DrawerLayout> Copy the code
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
      @Override
      public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
          // Home page content
          View contentView = drawerLayout.getChildAt(0);
 / / the sidebar  View menuView = drawerView;  // slideOffset is 0 or 1 by default  contentView.setTranslationX(menuView.getMeasuredWidth() * slideOffset);  }   @Override  public void onDrawerOpened(@NonNull View drawerView) {}   @Override  public void onDrawerClosed(@NonNull View drawerView) {}   @Override  public void onDrawerStateChanged(int newState) {}  }); Copy the code

Tip: Imitation QQ sideslip menu effect, here does not use the ToolBar, directly captured 2 pictures show.

7. Manual control menu

By default, swipe to Open the menu and click Close in the blank. But to avoid the need to click events to trigger the menu state, DrawerLayout design is very user-friendly and provides the following methods to achieve:

  1. openDrawer(View drawerView)

    Opens the specified drawer view and animates it into the view.

  2. closeDrawer(View drawerView)

    Closes the specified drawer view and animates it into the view.

  3. closeDrawers()

    Close all currently open drawer views by animating their view.

Examples:

// Open the left menu
mDrawerLayout.openDrawer(GravityCompat.START);
// Open the right menu
mDrawerLayout.openDrawer(GravityCompat.END);
// Close menu 6 on the left
mDrawerLayout.closeDrawer(GravityCompat.START); // Close all menus mDrawerLayout.closeDrawers(); Copy the code

Source code download contains Material Design series control set, regularly updated, please look forward to!

Eight, summary

Android Material Design Library has been launched for a long time. More and more apps use controls that conform to the Library package. DrawerLayout is definitely one of the popular ones. Material Design defines what a drawer navigation should look and feel like, unifying swipe menus and styles. DrawerLayout+NavigationView is used to the extreme on Android native phones.

Thank you so much for reading this article! Your praise and comments are the biggest motivation for my creation!

My WeChat: Jaynm888

Programmer interview networking group: 764040616

Android programmers are cordially invited to join the wechat communication group. The public account can reply to the wechat group or add my wechat invitation to join the group.