背景
DrawerLayout 介绍
DrawerLayout
是一种布局,可以实现两个界面,一个是主屏幕,另一个是通过滑动的方式将一些隐藏的菜单显示出来,最显著的例子便是 Google play store。DrawerLayout
的布局文件中可以放两个同级的控件,其中第一个为主屏幕的显示内容,第二个为侧边滑动菜单的显示内容。形式如下:
<?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"
tools:context=".MainActivity">
<主屏幕的布局内容>
.
.
</主屏幕的布局内容>
<侧边滑动菜单的布局内容
android:layout_gravity="start" />
</androidx.drawerlayout.widget.DrawerLayout>
注意,滑动菜单中必须指定android:layout_gravity=""
,这代表该菜单所属的位置在左边还是右边。
NavigationView 介绍
想要实现 Google play store 的滑动菜单的样式,可以使用NavigationView
来实现,该控件可以大致分为上下两个部分,上面的区域为HeaderView
,下面的区域为具体的菜单选项分布。
实现
文中会使用将图片圆形化的方式展示用户的头像,因此需要在app/build.gradle
中添加依赖:
implementation 'de.hdodenhof:circleimageview:3.0.1'
在实现 NavigationView 之前首先准备 menu 与 headerLayout 两个部分
-
menu 实现:
-
首先为了展示菜单选项左边的图标,首先需要准备好相应的素材,这里使用图标库自带的图标(在 drawable 文件夹上右击新建一个
Verctor Asset
,再选择Asset Type
中的Clip Art
,最后点击下面Clip Art
右边的图标即可选择自带图标库中的图标)。 -
右键点击
res
新建文件夹名为menu
的文件夹,在menu
中新建文件(文件及类型名为:nav_menu.xml
),内容为:<?xml version="1.0" encoding="UTF-8" ?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/myAppAndGames" android:icon="@drawable/ic_baseline_apps_24" android:title="My app & games" /> <item android:id="@+id/notification" android:icon="@drawable/ic_baseline_notifications_24" android:title="Notification" /> <item android:id="@+id/subscription" android:icon="@drawable/ic_baseline_subscriptions_24" android:title="Subscription" /> <item
-