1.布局代码
![](https://img.haomeiwen.com/i13299289/3f4bd2b949aa821c.png)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context=".MainActivity">
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
/>
</android.support.v4.widget.DrawerLayout>
<!--这里是主视图-->
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>...
2.布局二
![](https://img.haomeiwen.com/i13299289/fe5a7ffc48a1738f.png)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context=".MainActivity">
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!--这里是主视图-->
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="@android:color/holo_green_light"
/>
</android.support.v4.widget.DrawerLayout>
</android.support.constraint.ConstraintLayout>
3.mainActivity中的代码:
private void initDrawerLayout() {
//向系统设置toolbar
setSupportActionBar(toolbar);
//设置线性管理器
LinearLayoutManager manager = new LinearLayoutManager(this);
//ActionBarDrawerToggle 是 DrawerLayout.DrawerListener实现,改变android.R.id.home返回图标。
//.Drawer拉出、隐藏,带有android.R.id.home动画效果。.监听Drawer拉出、隐藏;
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// drawer.setDrawerListener(toggle);
//上面的监听被下面的就监听给取代了,由于回报空指针异常,google推出了addDrawerListener(),
// 对它做了空指针的判断
drawerLayout.addDrawerListener(toggle);
//该方法会自动和actionBar关联, 将开关的图片显示在了action上,如果不设置,也可以有抽屉的效果,不过是默认的图标
toggle.syncState();
}
网友评论