android中实现一个DrawerLayout滑动菜单

activity_drawer_layout.xml:

xml version="1.0" encoding="utf-8"?>
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

            android:layout_width="match_parent"
        android:layout_height="match_parent">
                            android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/colorPrimary"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    

            android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:textSize="30sp"
        android:textColor="#FFFFFF"
        android:background="#000000"
        android:text="This is menu" />

DrawerLayoutActivity.java:

package com.example.administrator.fromnew;

import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

public class DrawerLayoutActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_layout);
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);//得到DrawerLayout实例
        ActionBar actionBar = getSupportActionBar();//得到ActionBar实例
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);//让导航栏按钮显示出来,Toolbar最左侧的按钮就是HomeAsUp
            actionBar.setHomeAsUpIndicator(R.drawable.arrow_right_32px);//设置导航按钮图标
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case android.R.id.home://HomeAsUp的ID永远都是android.R.id.home
                mDrawerLayout.openDrawer(GravityCompat.START);//调用方法将滑动菜单展开,这里传入参数GravityCompat.START是为了保证这里的行为和XML中定义的一致
                break;
        }
        return true;
    }
}

你可能感兴趣的:(Android)