Material Design 实战 之第二弹——滑动菜单详解&实战(DrawerLayout & NavigationView)

简介: 本模块共有六篇文章,参考郭神的《第一行代码》,对Material Design的学习做一个详细的笔记,大家可以一起交流一下:Material Design 实战 之第一弹——Toolbar(即本文)Material Design 实战 之第二弹...

本模块共有六篇文章,参考郭神的《第一行代码》,对Material Design的学习做一个详细的笔记,大家可以一起交流一下:




文章提要与总结


1. DrawerLayout
        控件用处:实现滑动菜单

        1.1 首先它是一个布局,在布局中允许放入两个直接子控件,
        第一个子控件是主屏幕中显示的内容;
        第二个子控件是滑动菜单中显示的内容;
                关于第二个子控件有一点需要注意,layout_gravity这个属性是必须指定的:left   right   start
        
        1.2 添加导航按钮:

        1.2.1 首先调用findViewById()方法得到了DrawerLayout的实例;
        1.2.2 getSupportActionBar()方法得到了ActionBar的实例;
        1.2.3 调用ActionBar的setDisplayHomeAsUpEnabled()让导航按钮显示出来;
        1.2.4 调用了setHomeAsUpIndicator()方法来设置一个导航按钮图标;
        1.2.5 在onOptionsItemSelected()中对HomeAsUp按钮的点击事件进行处理——调用DrawerLayout的openDrawer()方法将滑动菜单展示出来;
                注意openDrawer()方法要求传入一个Gravity参数,
            为了保证这里的行为和XML中(DrawerLayout标签下的第二个直接子控件的android:layout_gravity值)定义的一致,
            我们传入了GravityCompat.START;
        1.2.6 实际上Toolbar最左侧的这个按钮就叫作HomeAsUp按钮,它默认的图标是一个返回的箭头,含义是返回上一个活动;
              这里将其换了图标,并将逻辑响应修改了;
              HomeAsUp按钮的id永远都是android.R.id.home!!!

2. NavigationView
        控件用处:轻松布局华丽炫酷的滑动菜单页面;
        2.1 添加了两行依赖关系
                compile 'com.android.support:design:24.2.1'
                compile 'de.hdodenhof:circleimageview:2.1.0'
    2.2
          在开始使用NavigationView之前,我们还需要提前准备好两个东西:menu和headerLayout。
        2.2.1 menu是用来在NavigationView中显示具体的菜单项的;
                  为Menu resource file;
                  在<menu>中嵌套了一个<group>标签
                      <group>标签下的<item>:
                        android:id属性指定菜单项的id,
                        android:icon属性指定菜单项的图标,
                        android:title属性指定菜单项显示的文字。
        2.2.2 headerLayout则是用来在NavigationView中显示头部布局的。
                  为Layout resourcefile;
    2.3 使用NavigationView
            添加android.support.design.widget.NavigationView标签,
                使用app:menu="@menu/nav_menu"
                app:headerLayout="@layout/nav_header"
                将menu和headerLayout设置完毕




正文


img_1970b49a93681528a99d1127c9be2833.png
最终成果图



DrawerLayout

关于滑动菜单和DrawerLayout,郭神如是说:

img_879143b50e3a489b1dba50286ad66ce0.png

img_bbe212e088c722c062361246b0c03d98.png
<?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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android: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:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </FrameLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:text="This is menu"
        android:textSize="30sp"
        android:background="#FFF"/>

</android.support.v4.widget.DrawerLayout>

可见这里最外层的控件使用了DrawerLayout,这个控件是由support-v4库提供的。

DrawerLayout中放置了两个直接子控件:
第一个子控件是FrameLayout,用于作为主屏幕中显示的内容,当然里面还有我们刚刚定义的Toolbar。
第二个子控件这里使用了一个TextView,用于作为滑动菜单中显示的内容,其实使用什么都可以,DrawerLayout并没有限制只能使用固定的控件。

但是关于第二个子控件有一点需要注意,layout_gravity这个属性是必须指定的,
因为我们需要告诉DrawerLayout滑动菜单是在屏幕的左边还是右边,
指定left表示滑动菜单在左边;
指定right表示滑动菜单在右边;
这里指定了start,表示会根据系统语言进行判断,如果系统语言是从左往右的,比如英语、汉语,滑动菜单就在左边,如果系统语言是从右往左的,比如阿拉伯语,滑动菜单就在右边。

现在重新运行一下程序,然后在屏幕的左侧边缘向右拖动,就可以让滑动菜单显示出来了,如图:

img_3484b7c17a98953348979458fde2b77e.png
img_7fad21eca41c620a3998920791049c26.png
img_d01131f05bd2b30d94d09569fdd7a71b.png
img_b8a564a411a20755deff59ce8c62673a.png
img_f09b3bfe62fd495653934ff8cd299d8f.png

这里我们并没有改动多少代码,

  • 首先调用findViewById()方法得到了DrawerLayout的实例,
  • 然后调用getSupportActionBar()方法得到了ActionBar的实例,虽然这个ActionBar的具体实现是由Toolbar来完成的。
  • 接着调用ActionBar的setDisplayHomeAsUpEnabled()方法让导航按钮显示出来,
  • 又调用了setHomeAsUpIndicator()方法来设置一个导航按钮图标。

实际上,Toolbar最左侧的这个按钮就叫作HomeAsUp按钮,它默认的图标是一个返回的箭头,含义是返回上一个活动。很明显,这里我们将它默认的样式(该按钮图标)和作用(改/设置了按钮点击事件)都进行了修改。

接下来在onOptionsItemSelected()方法中对HomeAsUp按钮的点击事件进行处理,
HomeAsUp按钮的id永远都是android.R.id.home;

切记是android.R.id.home,如果写成R.id.home是实现不了功能的!

然后调用DrawerLayout的openDrawer()方法将滑动菜单展示出来;
注意openDrawer()方法要求传入一个Gravity参数,为了保证这里的行为和XML中定义的一致,我们传入了GravityCompat.START

当前MainActivity全文:

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);//让导航按钮显示出来
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);//设置一个导航按钮图标
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.backup:
                Toast.makeText(this,"You clicked Backup" , Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(this,"You clicked Delete" , Toast.LENGTH_SHORT).show();
                break;
            case R.id.settings:
                Toast.makeText(this,"You clicked Settings" , Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }

}

运行程序,效果如下:

img_5e56596dee074feaa13666a68ab3b87e.png

可见在Toolbar的最左边出现了一个导航按钮,用户看到这个按钮就知道这肯定是可以点击的。
现在点击一下这个按钮,滑动菜单界面就会再次展示出来了。



NavigationView


img_154c3a38f13752a1bdb314b8f05f48ec.png
img_b85b3818dadf4ae9e2d4a7a17806c918.png
img_b5c77c7060ce2e07b984691bc6f025c8.png

首先这个控件是DesignSupport库中提供的,需要将这个库引入到项目中。
打开app/build.gradle文件,在dependencies闭包中添加依赖:

img_31df2eac483d976f9985738c1c982a47.png

    compile 'com.android.support:design:24.2.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'

这里添加了两行依赖关系,
第一行就是DesignSupport库,
第二行是一个开源项目CircleImageView,它可以用来轻松实现图片圆形化的功能,我们待会就会用到它。
CircleImageView的项目主页地址是:https://github.com/hdodenhof/CircleImageView

!!!
在开始使用NavigationView之前,我们还需要提前准备好两个东西:menu和headerLayout
menu是用来在NavigationView中显示具体的菜单项的;
headerLayout则是用来在NavigationView中显示头部布局的。


1/4.准备menu

我们先来准备menu,这里我事先找了几张图片来作为按钮的图标,并将它们放在了drawable-xxhdpi目录下。然后右击menu文件夹→New→Menu resource file,创建一个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/nav_call"
            android:icon="@drawable/nav_call"
            android:title="Call"/>
        <item
            android:id="@+id/nav_friends"
            android:icon="@drawable/nav_friends"
            android:title="Friends"/>
        <item
            android:id="@+id/nav_location"
            android:icon="@drawable/nav_location"
            android:title="Location"/>
        <item
            android:id="@+id/nav_mail"
            android:icon="@drawable/nav_mail"
            android:title="Mail"/>
        <item
            android:id="@+id/nav_task"
            android:icon="@drawable/nav_task"
            android:title="Tasks"/>
    </group>

</menu>

img_520a6568019c823b4f2be2c9be9f5960.png
我们首先在<menu>中嵌套了一个<group>标签,
然后将group的checkableBehavior属性指定为singlegroup表示一个组,
checkableBehavior指定为single表示组中的所有菜单项只能单选;

那么下面我们来看一下这些菜单项吧。这里一共定义了5个item,
分别使用
android:id属性指定菜单项的id,
android:icon属性指定菜单项的图标,
android:title属性指定菜单项显示的文字。
就是这么简单,现在我们已经把menu准备好了。


2/4.准备headerLayout

接下来应该准备headerLayout了,这是一个可以随意定制的布局,不过这里不将它做得太复杂。我们就在headerLayout中放置头像、用户名、邮箱地址这3项内容吧;
说到头像,那我们还需要再准备一张图片,这里找了一张宠物图片,并把它放在了drawable-xxhdpi目录下。
另外这张图片最好是一张正方形图片,因为待会我们会把它圆形化。
然后右击layout文件夹→New→Layout resourcefile,创建一个nav_header.xml文件。
修改其中的代码,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:padding="10dp"
    android:background="?attr/colorPrimary">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/icon_image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@drawable/nav_icon"
        android:layout_centerInParent="true"/>

    <TextView
        android:id="@+id/mail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="8267*****@qq.com"
        android:textColor="#FFF"
        android:textSize="14sp"/>

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/mail"
        android:text="wanchuangxiaoyun"
        android:textColor="#FFF"
        android:textSize="14sp"/>

</RelativeLayout>

可以看到,布局文件的最外层是一个RelativeLayout,我们将它的
宽度设为match_parent,
高度设为180dp,
这是一个NavigationView比较适合的高度,然后
指定它的背景色为colorPrimary;

在RelativeLayout中我们放置了3个控件,
CircleImageView是一个用于将图片圆形化的控件,它的用法非常简单,基本和ImageView是完全一样的,这里给它指定了一张图片作为头像,然后设置为居中显示。
另外两个TextView分别用于显示用户名和邮箱地址,它们都用到了一些RelativeLayout的定位属性;


3/4.使用NavigationView

现在menu和headerLayout都准备好了,我们终于可以使用NavigationView了。
修改activitymam.xml中的代码,如下所示:

<?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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android: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:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/nav_menu"
        app:headerLayout="@layout/nav_header">

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

可见这里将之前的TextView换成了NavigationView,这样滑动菜单中显示的内容也就变成NavigationView了。
这里又通过app:menu和app:headerLayout将我们刚才准备好的menu和headerLayout设置了进去,
android:layout_gravity="start"则是跟上面的textview一个道理了,用于指明滑动菜单的滑动位置,
这样NavigationView就定义完成了。

接下来还要去处理菜单项的点击事件。修改MainActivity中的代码:

img_7c18f86cd7600f163a0892870f50e5e3.png

代码还是比较简单的,
这里首先获取到了NavigauonView的实例,
然后调用它的setCheckedItem()方法将Call菜单项设置为默认选中。

接着调用了setNavigationItemSelectedListener()方法来设置一个菜单项选中事件的监听器,当用户点击了任意菜单项时,就会回调到onNavigationItemSelected()方法中。
我们可以在这个方法中写相应的逻辑处理,不过这里并没有附加任何逻辑,只是调用了DrawerLayout的closeDrawers()方法将滑动菜单关闭,这也是合情合理的做法。

下面是当前MainActivity.java的全文:

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);//让导航按钮显示出来
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);//设置一个导航按钮图标
        }

        navView.setCheckedItem(R.id.nav_call);//将Call菜单项设置为默认选中
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                mDrawerLayout.closeDrawers();//关闭滑动菜单
                return true;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.backup:
                Toast.makeText(this,"You clicked Backup" , Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(this,"You clicked Delete" , Toast.LENGTH_SHORT).show();
                break;
            case R.id.settings:
                Toast.makeText(this,"You clicked Settings" , Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }

}

现在可以重新运行一下程序了,点击一下Toolbar左侧的导航按钮,效果如图所示:

img_f8a66cc53c0f052d5341fb49ee25dd55.png

怎么样?这样的滑动菜单页面,你无论如何也不能说它丑了吧?MaterialDesign的魅力就在
这里,它真的是一种非常美观的设计理念,只要你按照它的各种规范和建议来设计界面,最终做
出来的程序就是特别好看的。
——郭霖大神

目录
相关文章
|
iOS开发
SwiftUI极简教程13:NavigationView导航栏使用
SwiftUI极简教程13:NavigationView导航栏使用
1711 2
SwiftUI极简教程13:NavigationView导航栏使用
|
XML Android开发 数据格式
Material Design 实战 之第二弹——滑动菜单详解&实战(DrawerLayout & NavigationView)
Material Design 实战 之第二弹——滑动菜单详解&实战(DrawerLayout & NavigationView)
Material Design 实战 之第五弹 —— 下拉刷新(SwipeRefreshLayout)
Material Design 实战 之第五弹 —— 下拉刷新(SwipeRefreshLayout)
Material Design 实战 之第三弹—— 悬浮按钮和可交互提示(FloatingActionButton & Snackbar & CoordinatorLayout)
Material Design 实战 之第三弹—— 悬浮按钮和可交互提示(FloatingActionButton & Snackbar & CoordinatorLayout)
|
Android开发
Material Design 实战 之第一弹——Toolbar详解
Material Design 实战 之第一弹——Toolbar详解
Material Design 实战 之第四弹 —— 卡片布局以及灵动的标题栏(CardView & AppBarLayout)
Material Design 实战 之第四弹 —— 卡片布局以及灵动的标题栏(CardView & AppBarLayout)
|
Android开发 容器
[译]Flutter学习笔记:BottomNavigationBar实现多个Navigation
这个文章解决了什么问题? 最近我研究了一下Flutter,但是在使用Navigator的时候遇到了一个很头痛的问题,就是当我们去来回切换导航按钮时,Flutter会重新build,从而导致控件重新Build,从而会失去浏览历史。
1757 0
个人总结:关于使用design库中FloatingActionButton等控件的说明
主要看博客平台上很少提及的要说的问题,所以这里写出来做个标识,供大家参考。 文章纯属个人总结,以后会出这些控件的使用说明,这里只是说下要使用design库中的各种控件的注意的地方: 1 、使用这些控件大家应该都知道所在的activity都必须继承app...
739 0