滑动菜单--DrawerLayout

DrawerLayout是一个布局,在布局里面只允许放两个直接子控件,第一个是主屏幕显示的内容,第二个是滑动菜单中显示的内容。,第二个子控件加黑需要注意,必须添加,该属性是指,在手机哪一侧划出菜单,star根据系统语言进行判断,left,由左向右划出,right相反

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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.ca.sd.zsl.toolbartest"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ca.sd.zsl.toolbartest.MainActivity">

    <FrameLayoutandroid:layout_width="match_parent"
        android:layout_height="match_parent">
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    </FrameLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
     android:text="这是策划菜单"
/> </android.support.v4.widget.DrawerLayout>

在ToolBar上添加按钮弹出菜单,

  //设置按钮弹出菜单
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);先获取布局实例,
        ActionBar actionBar = getSupportActionBar();然后获取ActionBar实例,
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);让按钮显示出来
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);设置图片
        }

home按钮的点击事件,重写onOptionsItemSelected方法。

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            /**
             * 在ToolBar最左侧的图标就叫做HomeAsUp按钮,含义是返回上一个活动,
             * 它的ID永远是android.R.id.home
             */
            case android.R.id.home:
STAR:打开视图到x轴的开始位置,不改变大小,END:打开视图到x轴的结束位置,不改变大小 mDrawerLayout.openDrawer(GravityCompat.START);
break;default: break; } return true; }
原文地址:https://www.cnblogs.com/zhoushenglei/p/7222431.html