前言
DrawerLayout 是 Support Library 包中实现了侧滑菜单效果的控件,可以说 DrawerLayout 是因为第三方控件如 MenuDrawer 等的出现之后,google 借鉴而出现的产物。DrawerLayout 分为侧边菜单和主内容区两部分,侧边菜单可以根据手势展开与隐藏(DrawerLayout 自身特性),主内容区的内容可以随着菜单的点击而变化。
一、DrawerLayout 基础使用
DrawerLayout 其实是一个布局控件,继承 ViewGroup,与 LinearLayout 等控件是一种东西,属于同级控件。但是 DrawerLayout 带有滑动的功能。只要按照 DrawerLayout 的规定布局方式写完布局,就能有侧滑的效果。
DrawerLayout 最简单的使用方式,添加 2 个子布局,分别代表 APP 主页面和侧滑菜单页面。
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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.com/tools"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--主页面-->
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@mipmap/meizi_2" />
<!--侧滑菜单页面-->
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@mipmap/pangzi" />
</androidx.drawerlayout.widget.DrawerLayout>
完成上面的布局文件,就可以实现如下效果:
二、DrawerLayout + ToolBar 使用
日常开发中,每个界面都会有一个 ToolBar,并且侧滑出来的内容都会在 ToolBar 的底部。最常见的就是 ToolBar 左侧会有一个小图标(号称三道杠),在侧滑菜单展示时,会加载一个动画变成返回按钮,完成这个效果不需要在 ToolBar 上自己添加 Icon,只需要借助 ActionBarDrawerToggle 类就可实现。
ActionBarDrawerToggle 效果就是一个“三“ 然后点击变”←“
ActionBarDrawerToggle 的作用:
- 改变 android.R.id.home 返回图标
- DrawerLayout 拉出、隐藏,带有 android.R.id.home 动画效果
- 监听 DrawerLayout 拉出、隐藏
因为要实现侧滑菜单在 ToolBar 底部,修改 XML 文件,将 ToolBar 放在 DrawerLayout 布局外层。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:title="DrawerLayout"
tools:ignore="MissingConstraints" />
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@mipmap/meizi_2" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@mipmap/pangzi" />
</androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>
// 设置左上角图标["三" —— "←"]效果
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.<