DrawerLayout和NavigationView使用詳解

Android Material Design Library 推出了很長時間,越來越多的APP使用了符合Library 包的控件,DrawerLayout絕對是熱門之一,Material Design定義了一個抽屜導(dǎo)航應(yīng)該有何種外觀和感受,統(tǒng)一了側(cè)滑菜單和樣式。在Android原生手機(jī)上對DrawerLayout+NavigationView更是使用到了極致,如Gmail,Google Map

關(guān)于DrawerLayout和NavigationView的使用介紹博客有很多,這里主要是實(shí)現(xiàn)一些使用上的介紹,如讓NavigationView在Toolbar下方,不顯示Toolbar左側(cè)按鈕等。

下面開始看下DrawerLayout的如何使用,首先在build.gradle中引入Design包

compile 'com.android.support:design:24.2.1'

(一)、基本使用

新建一個Activity,這里我們選擇使用Android Studio提供的模板,選擇NavgationDrawer Activity


QQ截圖20161118143554.jpg

查看下界面的xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    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:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_drawer_layout__one"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_drawer_layout__one"
        app:menu="@menu/activity_drawer_layout__one_drawer"/>

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

可以看到我們的最外層是DrawerLayout,包含了兩個內(nèi)容:include為顯示內(nèi)容區(qū)域,NavigationView為側(cè)邊抽屜欄。

NavigationView有兩個app屬性,分別為app:headerLayout和app:menu,eaderLayout用于顯示頭部的布局(可選),menu用于建立MenuItem選項(xiàng)的菜單。

headerLayout就是正常的layout布局文件,我們查看下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_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import"/>
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery"/>
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow"/>
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools"/>
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share"/>
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send"/>
        </menu>
    </item>
</menu>

menu可以分組,group的android:checkableBehavior屬性設(shè)置為single可以設(shè)置該組為單選

Activity主題必須設(shè)置先這兩個屬性

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

未設(shè)置Activity主題會爆出錯誤信息:

vCaused by: java.lang.IllegalStateException: This Activity 
already has an action bar supplied by the window decor. 
Do not request Window.FEATURE_SUPPORT_ACTION_BAR 
and set windowActionBar to false in your theme to use a Toolbar instead.

設(shè)置主題為android:theme="@style/AppTheme.NoActionBar"

最后java代碼

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

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

效果圖:


GIF.gif

(二)、監(jiān)聽和關(guān)閉NavigationView

NavigationView監(jiān)聽通過navigationView.setNavigationItemSelectedListener(this)方法去監(jiān)聽menu的點(diǎn)擊事件

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item)
{
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

每次點(diǎn)擊一個Menu關(guān)閉DrawerLayout,方法為drawer.closeDrawer(GravityCompat.START);

通過onBackPressed方法,當(dāng)點(diǎn)擊返回按鈕的時候,如果DrawerLayout是打開狀態(tài)則關(guān)閉

    @Override
    public void onBackPressed()
    {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

(三)、NavigationView在Toolbar下方

大多數(shù)的APP都是使用NavigationView都是全屏的,當(dāng)我們想讓NavigationView在Toolbar下方的時候應(yīng)該怎么做呢
xml布局如下圖,DrawerLayout在Toolbar的下方

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:id="@+id/sample_main_layout"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

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

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:padding="16dp"
                android:text="NavigationView在Toolbar下方"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_drawer_layout_one"
            app:menu="@menu/activity_drawer_layout_one_drawer"/>

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

效果如圖:


NavigationView在Toolbar下方.gif

(四)、Toolbar上不顯示Home旋轉(zhuǎn)開關(guān)按鈕

上圖可以看到我們點(diǎn)擊Home旋轉(zhuǎn)開關(guān)按鈕,顯示和隱藏了側(cè)滑菜單。那么如果我們想要不通過按鈕點(diǎn)擊,只能右劃拉出菜單需要怎么做呢。
我們先看下帶Home旋轉(zhuǎn)開關(guān)按鈕的代碼是如何寫的:

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//這是帶Home旋轉(zhuǎn)開關(guān)按鈕
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, 
    toolbar, 
    R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

這個Home旋轉(zhuǎn)開關(guān)按鈕實(shí)際上是通過ActionBarDrawerToggle代碼綁定到toolbar上的,ActionBarDrawerToggle是和DrawerLayout搭配使用的,它可以改變android.R.id.home返回圖標(biāo),監(jiān)聽drawer的顯示和隱藏。ActionBarDrawerToggle的syncState()方法會和Toolbar關(guān)聯(lián),將圖標(biāo)放入到Toolbar上。
進(jìn)入ActionBarDrawerToggle構(gòu)造器可以看到一個不傳Toolbar參數(shù)的構(gòu)造器

public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
        @StringRes int openDrawerContentDescRes,
        @StringRes int closeDrawerContentDescRes) {
    this(activity, null, drawerLayout, null, openDrawerContentDescRes,
            closeDrawerContentDescRes);
}

那么不帶Home旋轉(zhuǎn)開關(guān)按鈕的代碼如下

//這是不帶Home旋轉(zhuǎn)開關(guān)按鈕
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer,
  R.string.navigation_drawer_open, R.string.navigation_drawer_close);

當(dāng)然我們把上面帶Home旋轉(zhuǎn)開關(guān)按鈕的代碼刪除也是可以的。

效果如圖:


Toolbar上不顯示Home旋轉(zhuǎn)開關(guān)按鈕.gif

(五)、不使用NavigationView,使用DrawerLayout+其他布局

APP實(shí)際開發(fā)中往往不能完全按照Materialdesign的規(guī)則來,如網(wǎng)易云音樂的側(cè)滑,底部還有兩個按鈕。這時候我們可以通過+其他布局來實(shí)現(xiàn)特殊的側(cè)滑布局。

我們可以參考鴻楊大神的博客
Android 自己實(shí)現(xiàn) NavigationView [Design Support Library(1)]

我們自己實(shí)現(xiàn)個簡單的,DrawerLayout包裹了一個FrameLayout和一個RelativeLayout,FrameLayout是我們的顯示內(nèi)容區(qū)域,RelativeLayout是我們的側(cè)邊欄布局。

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    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:fitsSystemWindows="true"
    tools:openDrawer="start">

    <FrameLayout
        android:id="@+id/container"
        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"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:padding="16dp"
            android:text="@string/title_activity_drawer_layout_other"/>
    </FrameLayout>

    <RelativeLayout
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        android:fitsSystemWindows="true">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="這是頂部按鈕"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="這是中間的按鈕"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="這是底部按鈕"/>
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>

如果需要監(jiān)聽DrawerLayout的側(cè)滑狀態(tài)監(jiān)聽,那么代碼如下:

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        /**
         * 也可以使用DrawerListener的子類SimpleDrawerListener,
         * 或者是ActionBarDrawerToggle這個子類
         */
        mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        });

效果圖如下:

DrawerLayout+其他布局.gif

最后上github地址

https://github.com/itdais/MaterialDesignDing

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,367評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,001評論 3 413
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,213評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,535評論 1 308
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,317評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,868評論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,963評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,090評論 0 285
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,599評論 1 331
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,549評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,712評論 1 367
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,233評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 43,961評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,353評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,607評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,321評論 3 389
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,686評論 2 370

推薦閱讀更多精彩內(nèi)容