Menu writing example of DrawerLayout drawer effect in Android App, drawerlayout upper and lower drawer_PHP tutorial

WBOY
Release: 2016-07-12 08:56:15
Original
1397 people have browsed it

Menu writing example of DrawerLayout drawer effect in Android App, drawerlayout upper and lower drawers

Navigation menu of drawer effect
After looking at many applications, I think this side-sliding drawer effect menu is very good.

2016321171423565.png (206×345)

There is no need to switch to another page or press the hardware button of the menu. Just click a button on the interface and the menu will slide out, and it feels like it can hold a lot of things.
Library reference:
First of all, the DrawerLayout class is in the Support Library, and the android-support-v4.jar package needs to be added.

Then import android.support.v4.widget.DrawerLayout;

If you cannot find this class, first use the SDK Manager to update the Android Support Library, then find android-support-v4.jar in the Android SDKextrasandroidsupportv4 path, copy it to the libs path of the project, and add it to 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" >

  <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 -->
    <!-- main content must be the first element of DrawerLayout because it will be drawn first and drawer must be on top of it -->

    <FrameLayout
      android:id="@+id/content_frame"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

    <!-- The navigation drawer -->

    <ListView
      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:dividerHeight="0dp" />
  </android.support.v4.widget.DrawerLayout>

</RelativeLayout> 

Copy after login

The first child element of DrawerLayout is the main content, that is, the layout displayed when the drawer is not opened. A FrameLayout is used here with nothing in it.

The second child element of DrawerLayout is the content in the drawer, that is, the drawer layout. A ListView is used here.

Main Activity (taken 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.drawable.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 closed state. */
      public void onDrawerClosed(View view)
      {

        invalidateOptionsMenu(); // creates call to
                      // onPrepareOptionsMenu()
      }

      /** Called when a drawer has settled in a completely open state. */
      public void onDrawerOpened(View drawerView)
      {

        invalidateOptionsMenu(); // creates call to
                      // 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 11
  }

  private void initListView()
  {
    mDrawerList = (ListView) findViewById(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<&#63;> parent, View view,
          int position, long id)
      {
        // Highlight 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(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    // Pass the event to ActionBarDrawerToggle, if 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);
  }

}

Copy after login

What is more confusing is the use of an API of Level 11, so the minSdkVersion is limited and cannot be too low.

Picture resources are available for download from the sample on the Android official website.

The effect after running the program is as follows:
Before drawer opening:

2016321171457025.jpg (720×1280)

After the drawer is opened:

2016321171528332.jpg (720×1280)

Code 2
Today I took another look at the DrawerLayout class and found that there are many methods that can be used directly.

I tried it again. In fact, it doesn’t have to be as troublesome as above. You can just define a button to control the opening of the drawer:

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 -->

    <FrameLayout
      android:id="@+id/content_frame"
      android:layout_width="match_parent"
      android:layout_height="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/left_drawer"
      android:layout_width="240dp"
      android:layout_height="match_parent"
      android:layout_gravity="start"
      android:background="#111"
      android:choiceMode="singleChoice"
      android:divider="@android:color/transparent"
      android:dividerHeight="0dp" />
  </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

Copy after login


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)
      {
        // 按钮按下,将抽屉打开
        mDrawerLayout.openDrawer(Gravity.LEFT);

      }
    });
  }

}

Copy after login

Use Toolbar DrawerLayout to quickly realize high-end menu sliding
If you are paying attention to some applications that follow the latest Material Design design specifications (if not, assuming you are!), you may find that many use side-sliding menu animation effects that look very comfortable and elegant. , the example is as follows (via reference 2):

2016321171553612.gif (386×694)

Today, let’s use the official support library to quickly achieve this type of effect. You need to use Toolbar and DrawerLayout. The detailed steps are as follows: (If you don’t know these two Widgets, Google them first~)
First you need to add appcompat-v7 support:

If the project is created on Android Studio 1.0 RC4, appcompat-v7 support has been added by default. If it is not the latest version of AS, you need to add the following code to build.gradle:

dependencies {
  ...//其他代码
  compile 'com.android.support:appcompat-v7:21.0.2'
}
Copy after login

After adding, you need to synchronize gradle

Add Toolbar:

Since Toolbar inherits from View, you can add Toolbar directly to the main layout file like other standard controls. However, in order to improve the reuse efficiency of Toolbar, you can create a custom_toolbar.xml code in the layout as follows:

<&#63;xml version="1.0" encoding="utf-8"&#63;>
  <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="&#63;attr/colorPrimary"
    android:minHeight="&#63;attr/actionBarSize"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar">
</android.support.v7.widget.Toolbar>
Copy after login

Description:

android.support.v7.widget.Toolbar - Of course, if you only use Toolbar in Lollipop, you can use the Toolbar directly without adding v7 support
xmlns:app - Customized xml naming control, res-auto can be specified directly in AS without using the full package name
Both android:background and android:minHeight can be declared in styles.xml
Add DrawerLayout:

Similar to Toolbar, in order to improve code reuse efficiency, you can create a custom_drawerlayout.xml code in the layout as follows:

<&#63;xml version="1.0" encoding="utf-8"&#63;>
  <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:layout_height="match_parent">
  <!--主布局-->
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
      android:id="@+id/iv_main"
      android:layout_width="100dp"
      android:layout_height="100dp" />
  </LinearLayout>
  <!--侧滑菜单-->
  <LinearLayout
    android:layout_width="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>
</android.support.v4.widget.DrawerLayout>
Copy after login

There are two child nodes in the Drawerlayout tag, one is the left menu and the other is the main layout. In addition, the starting position of the left menu needs to be 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>
Copy after login

Use the include tag directly, concise and clear

Improve Java code:

public class MainActivity extends ActionBarActivity {
  //声明相关变量
  private Toolbar toolbar;
  private DrawerLayout mDrawerLayout;
  private ActionBarDrawerToggle mDrawerToggle;
  private ListView lvLeftMenu;
  private String[] lvs = {"List Item 01", "List Item 02", "List Item 03", "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(); //获取控件
    //京东RunningMan动画效果,和本次Toolbar无关
    mAnimationDrawable = (AnimationDrawable) ivRunningMan.getBackground();
    mAnimationDrawable.start();
    toolbar.setTitle("Toolbar");//设置Toolbar标题
    toolbar.setTitleTextColor(Color.parseColor("#ffffff")); //设置标题颜色
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //创建返回键,并实现打开关/闭监听
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close) {
      @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);
    //设置菜单列表
    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);
  }
}
Copy after login

Of course the more important ones are styles.xml and colors.xml, the details are as follows:

<resources>
  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!--状态栏颜色-->
    <item name="colorPrimaryDark">@color/Indigo_colorPrimaryDark</item>
    <!--Toolbar颜色-->
    <item name="colorPrimary">@color/Indigo_colorPrimary</item>
    <!--返回键样式-->
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>
    </style>
    <style name="AppTheme.DrawerArrowToggle" parent="Base.Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
  </style>
</resources>
<&#63;xml version="1.0" encoding="utf-8"&#63;>
<resources>
  <color name="Indigo_colorPrimaryDark">#303f9f</color>
  <color name="Indigo_colorPrimary">#3f51b5</color>
  <color name="Indigo_nav_color">#4675FF</color>
</resources>
Copy after login

At this point, the side-sliding menu on Gaodao has been realized, and the final effect is as follows (Note: It seems that directly recording the mobile phone screen does not work on Yosemite, and the animation cannot be real-time due to frame rate reasons, so let’s watch it like this first~)

Articles you may be interested in:

  • Android component DrawerLayout implements drawer menu
  • Android improved multi-directional drawer implementation method
  • Android control SlidingDrawer (Sliding drawer) Detailed explanation and example sharing
  • How to use the hidden layout drawer in android with advanced android UI
  • Achievement of Android SlidingDrawer drawer effect

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1113728.htmlTechArticleMenu writing example of DrawerLayout drawer effect in Android App, the navigation menu of drawerlayout upper and lower drawer drawer effect has been seen in many applications. I think this side-sliding drawer effect menu is very good...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!