Detailed explanation of drawerlayout usage of Android sideslip menu

Time:2020-2-26

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"><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">
  <! -- the main content view when the drawer is closed -- >
  <FrameLayout 
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
  </FrameLayout>
  <! -- the Navigation view left side opened Navigation view -- >
  <ListView 
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    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
    android:background="#ffffcc"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    ></ListView>
</android.support.v4.widget.DrawerLayout>

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;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 // mTitle=(String) getTitle();
 mDrawerLayout=(DrawerLayout) findViewById(R.id.drawer_layout);
 mListView=(ListView) findViewById(R.id.left_drawer);
 menuList=new ArrayList<String>();
 for(int i=0;i<5;i++)
  Menulist. Add ("Liu Jiawei" + I);
 adapter=new ArrayAdapter<String>(this,
  android.R.layout.simple_list_item_1,menuList);
 mListView.setAdapter(adapter);

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="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <TextView 
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="25sp"/>
</LinearLayout>

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.app.Fragment;
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;
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View view=inflater.inflate(R.layout.fragment_content,container,false);
 tv=(TextView) view.findViewById(R.id.tv);
 String text = getarguments(). GetString ("text"); // get the passed in value
 tv.setText(text); 
 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

@Override
 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 (r.id.content_frame, 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,
  R.string.drawer_open,R.string.drawer_close){
  @Override
  public void onDrawerOpened(View drawerView) {
  super.onDrawerOpened(drawerView);
  Getactionbar(). Settitle ("please select");
  Invalidateoptionsmenu(); // redraw the menu item on actionbar, and call onpreareoptionsmenu() when executing this method
  }
  @Override
  public void onDrawerClosed(View drawerView) {
  super.onDrawerClosed(drawerView);
  getActionBar().setTitle(mTitle);
  invalidateOptionsMenu();
  }
 };
 mDrawerLayout.setDrawerListener(mDrawerToggle);

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

res/values/menu/main.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.drawerlayout.MainActivity" >
<item
  android:id="@+id/websearch"
  android:icon="@drawable/action_search"
  android:showAsAction="ifRoom|withText"
  android:title="webSearch"
  />
</menu>

Then load the menu in


 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(R.menu.main, menu);
 return super.onCreateOptionsMenu(menu);
 }

Set the click event for this search button along the way

/*Set click event for websearch of actionbar*/
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case R.id.websearch:
  Intent intent=new Intent();
  intent.setAction("android.intent.action.VIEW");
  intent.setData(Uri.parse("http://www.baidu.com"));
  startActivity(intent);
  break;
 default:
  break;
 }
 return super.onOptionsItemSelected(item);
 }

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

@Override
 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 (r.id.websearch). 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
 getActionBar().setDisplayHomeAsUpEnabled(true);
 getActionBar().setHomeButtonEnabled(true);

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

@Override
 public boolean onOptionsItemSelected(MenuItem item) {
 //Combine the icon on the actionbar with the drawer
 if(mDrawerToggle.onOptionsItemSelected(item)){
  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()

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

Combining all the above, the renderings are as follows

summary

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