MD系列2、ToolBar+DrawerLayout + NavigationView

本文出自 “阿敏其人” 簡書博客,轉載或引用請注明出處。

一、Google口中的ToolBar

從Toolbar說起
ToolBar->android.support.v7.widget.Toolbar
Toolbar是在Android 5.0以后推出來的,之前都是ActionBar這個控件

Paste_Image.png

Google Toolbar 文檔

Google大概這么說

A standard toolbar for use within application content.

A Toolbar is a generalization of action bars for use within application layouts. While an action bar is traditionally part of an Activity's opaque window decor controlled by the framework, a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy. An application may choose to designate a Toolbar as the action bar for an Activity using the setSupportActionBar() method.

Toolbar supports a more focused feature set than ActionBar. From start to end, a toolbar may contain a combination of the following optional elements:

  • A navigation button. This may be an Up arrow, navigation menu toggle, close, collapse, done or another glyph of the app's choosing. This button should always be used to access other navigational destinations within the container of the Toolbar and its signified content or otherwise leave the current context signified by the Toolbar. The navigation button is vertically aligned within the Toolbar's minimum height, if set.
  • A branded logo image. This may extend to the height of the bar and can be arbitrarily wide.
  • A title and subtitle. The title should be a signpost for the Toolbar's current position in the navigation hierarchy and the content contained there. The subtitle, if present should indicate any extended information about the current content. If an app uses a logo image it should strongly consider omitting a title and subtitle.
  • One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view's Toolbar.LayoutParams indicates a Gravity value of CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.
  • An action menu. The menu of actions will pin to the end of the Toolbar offering a few frequent, important or typical actions along with an optional overflow menu for additional actions. Action buttons are vertically aligned within the Toolbar's minimum height, if set.

In modern Android UIs developers should lean more on a visually distinct color scheme for toolbars than on their application icon. The use of application icon plus title as a standard layout is discouraged on API 21 devices and newer.

其實大概是這個意思

Toolbar 是一個應用程序使用中的標準工具欄,Toolbar可以被嵌套在任意一個層級的View中。
相對ActionBar而言,Toolbar提供了更多牛逼的特性。ToolBar是api21 新增的組件,其主要用來彌補actionbar帶來的不足,其繼承自viewgroup,自由的屬性包括:

  • 導航按鈕(類似向上按鈕) (A navigation button)
  • logo圖片 (A branded logo image.)
  • 標題和子標題 (A title and subtitle)
  • 一個或者多個自定義view (One or more custom views.)
  • 菜單。 (An action menu.)
Paste_Image.png

需要特別注意的是:我們可以在任何activity中使用toolbar作為actiobar,但是api21之前只能使用setSupportActionbar(),相應的主題也要設置為NoActionbar.

二、簡單實用

最簡單的使用

1、引入庫
build.gradle

    compile 'com.android.support:appcompat-v7:23.4.0'

2、Actviity繼承自AppCompatActivity

public class MainActivity extends AppCompatActivity

3、Theme需要NoActionBar

<resources>

    <!-- Base application theme. -->
<!--    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!– Customize your theme here. –>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>-->

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

(如果Theme NoActionBar覺得不方便可以利用BaseActivity通知代碼設置一下,supportRequestWindowFeature(Window.FEATURE_NO_TITLE) )

4、布局實用ToolBar

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.am.toolbartest.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/mToolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        >
    </android.support.v7.widget.Toolbar>
</RelativeLayout>

5、Activity setSupportActionBar

public class MainActivity extends AppCompatActivity {
    private Toolbar mToolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToolBar = (Toolbar) findViewById(R.id.mToolBar);
        setSupportActionBar(mToolBar);
    }
}

注意:
ToolBar需要調用setSupportActionBar(ToolBar);方法,如果你的Activity是繼承自FragmentActivity,是沒有這個方法的。
解決方案:將你的Activity改成繼承自AppCompatActivity,(AppCompatActivity是FragmentActivity的直接子類)

運行效果:


Paste_Image.png

是的現在看起來low且平凡,現在先放任不管,把一些陌生的東西集中處理一下:

問題1、為什么style布局文件需要NoActionBar?
如果含有ActionBar,會和ToolBar沖突。所以必須在Style或者代碼指定,去掉ActionBar。

問題2、布局文件android:elevation="4dp" 是什么鬼?

android:elevation有海拔和立體的意思,大概就是有一點浮動的效果,更加美觀,不喜可刪。
material design 建議為app bar 的elevation設置為4dp。

問題3、 指定ToolBar的主題: android:theme="@style/ThemeOverlay.AppCompat.ActionBar"和app:popupTheme="@style/ThemeOverlay.AppCompat.Light" 是什么鬼?

android:theme="@style/ThemeOverlay.AppCompat.ActionBar",通過這句代碼,我們可以為不同頁面的ActionBar指定不同的主題樣式

app:popupTheme="@style/ThemeOverlay.AppCompat.Light",這鍋這句代碼,可以指定彈出的菜單的樣式

如果不加這兩句代碼,那么就是統一的默認主題樣式。
詳情可以參考一下鏈接:
正確使用 Android 的 Theme 和 Style
android:theme和app:popupTheme的作用,以及在android 3.0以下不起作用問題的解決

問題4、ToolBar的名字為何自帶標題?

在運行效果圖圖里面,我們看到Toolbar有自帶的標題,這是因為我們Activity里面調用了 setSupportActionBar(mToolBar);這句代碼。

當我們 setSupportActionBar(mToolBar); 而又沒有指定標題的時候,那么標題就是程序名。

三、上吧,五兄弟

我們之前說過,ToolBar可以包含

  • 導航按鈕(類似向上按鈕) (A navigation button)
  • logo圖片 (A branded logo image.)
  • 標題和子標題 (A title and subtitle)
  • 一個或者多個自定義view (One or more custom views.)
  • 菜單。 (An action menu.)

那么現在我們來添加一下
先加三個:
導航按鈕(類似向上按鈕) (A navigation button)
logo圖片 (A branded logo image.)
標題和子標題 (A title and subtitle)

        mToolBar.setTitle("Title");
        setSupportActionBar(mToolBar);

        mToolBar.setNavigationIcon(R.mipmap.nac_icon);
        mToolBar.setLogo(R.mipmap.sugar);
        mToolBar.setSubtitle("SubTit");

導航按鈕,logo圖片,沒什么提別的,
但是加標題的時候,mToolBar.setTitle("Title");必須在setSupportActionBar(mToolBar);之前設置標題才會生效

  • 一個或者多個自定義view

ToolBar繼承自ViewGroup,所以是個容器,可以放置View

Paste_Image.png

.
.

自定義View放置在ToolBar里面

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.am.toolbartest.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/mToolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        >

        <TextView
            android:id="@+id/mTvDiy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DIY"
            android:textColor="#fff"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            />
    </android.support.v7.widget.Toolbar>
</RelativeLayout>
  • 菜單

在menu下創建菜單文件,(如果menu文件夾不在則創建之)

Paste_Image.png

代碼

<?xml version="1.0" encoding="utf-8"?>
<menu 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"
    tools:context=".MainActivity" >
    <item android:id="@+id/action_ball"
        android:title="籃球"
        android:orderInCategory="80"
        android:icon="@mipmap/ball_icon"
        app:showAsAction="ifRoom" />
    <item android:id="@+id/action_tip"
        android:title="提醒"
        android:orderInCategory="90"
        android:icon="@mipmap/bell_icon"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_menu"
        android:title="設置"
        android:orderInCategory="90"
        android:icon="@mipmap/menu_icon"
        app:showAsAction="ifRoom" />
</menu>

showAsAction的值

app中有一個菜單(menu),showAsAction主要是針對這個菜單的顯示起作用的,它有三個可選項:

always:總是顯示在界面上
never:不顯示在界面上,只讓出現在右邊的三個點中
ifRoom:如果有位置才顯示,不然就出現在右邊的三個點中

.
.
創建關聯菜單

    // 創建關聯菜單
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }

.
.
菜單的點擊回調

    // 菜單的點擊回調
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            switch (menuItem.getItemId()) {
                case R.id.action_ball:
                    msg += "Click ball";
                    break;
                case R.id.action_tip:
                    msg += "Click action_tip";
                    break;
                case R.id.action_menu:
                    msg += "Click setting";
                    break;
            }
            if(!msg.equals("")) {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    };

.
.
設置菜單點擊監聽
mToolBar.setOnMenuItemClickListener(onMenuItemClick);

綜上,完整的MainActivity代碼如下:

public class MainActivity extends AppCompatActivity {
    private Toolbar mToolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToolBar = (Toolbar) findViewById(R.id.mToolBar);
        mToolBar.setTitle("Title");
        setSupportActionBar(mToolBar);

        mToolBar.setNavigationIcon(R.mipmap.nac_icon);
        mToolBar.setLogo(R.mipmap.sugar);
        mToolBar.setSubtitle("SubTit");
        // 設置菜單點擊監聽
        mToolBar.setOnMenuItemClickListener(onMenuItemClick);
    }

    // 菜單的點擊回調
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            switch (menuItem.getItemId()) {
                case R.id.action_ball:
                    msg += "Click ball";
                    break;
                case R.id.action_tip:
                    msg += "Click action_tip";
                    break;
                case R.id.action_menu:
                    msg += "Click setting";
                    break;
            }
            if(!msg.equals("")) {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    };


    // 創建關聯菜單
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }
}

.
.
效果圖:

Paste_Image.png

如果菜單項特別多,那么會在菜單的最右邊一向形成列表

<?xml version="1.0" encoding="utf-8"?>
<menu 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"
    tools:context=".MainActivity" >
    <item android:id="@+id/action_ball"
        android:title="籃球"
        android:orderInCategory="80"
        android:icon="@mipmap/ball_icon"
        app:showAsAction="ifRoom" />
    <item android:id="@+id/action_tip"
        android:title="提醒"
        android:orderInCategory="90"
        android:icon="@mipmap/bell_icon"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_menu"
        android:title="設置"
        android:orderInCategory="90"
        android:icon="@mipmap/menu_icon"
        app:showAsAction="ifRoom" />

    <item
        android:title="其他1"
        android:orderInCategory="90"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="ifRoom" />

    <item
        android:title="其他2"
        android:orderInCategory="90"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="ifRoom" />

    <item
        android:title="其他3"
        android:orderInCategory="90"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="ifRoom" />
</menu>

gif

較多.gif

Action Menu Item文本顏色

如果想要修改Menu Item的文本顏色,可以這么做

1、style Theme指定文本顏色、

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColorPrimary">#968e48</item> <!--指定顏色-->
    </style>

2、toolbar所在的xml文件指定我們自己的主題

    <!--app:popupTheme="@style/AppTheme" 指定主題-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/mToolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/AppTheme"  
        >

當item圖標較多,在Toolbar無法容下item,那么這時候Toolbar會在menu的最右邊生成一個菜單圖標(三個豎直排列的小點),有興趣可以改變menu文件嘗試一下。上面的代碼的我們自己也弄了一個一個豎直的三個小圖的菜單圖標,兩者不是同一個東西,需要區分一下。

四、回退帶主頁

ToolBar可以生成一個回退按鈕,按下就回退到主頁

1、在清單文件對應的activity添加對應的meta-data,鍵值的性質,指定主頁。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.am.toolbartest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IndexActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"/>

        <activity android:name=".MainActivity">
            <!-- Parent activity meta-data to support 4.0 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".IndexActivity" />
        </activity>
    </application>

</manifest>

.
.
2、MainActivity設定setDisplayHomeAsUpEnabled(true);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToolBar = (Toolbar) findViewById(R.id.mToolBar);
        mToolBar.setTitle("Title");
        setSupportActionBar(mToolBar);

        mToolBar.setNavigationIcon(R.mipmap.nac_icon);
        mToolBar.setLogo(R.mipmap.sugar);
        mToolBar.setSubtitle("SubTit");
        // 設置菜單點擊監聽
        mToolBar.setOnMenuItemClickListener(onMenuItemClick);

        // Get a support ActionBar corresponding to this toolbar
        ActionBar ab = getSupportActionBar();

        // Enable the Up button
        ab.setDisplayHomeAsUpEnabled(true);
    }

返回主頁效果圖

返回主頁.gif

如果只想回退到上一頁

mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

五、 Action View

利用Action View,可以更好利用ToolBar的空間,比如ToolBar上面有一個搜索按鈕,平時是一個圖片,搜索時就變成一個 搜索欄 。

搜索.gif

在Toolbar/Actionbar中添加SearchView實現搜索功能

Action Views 和 Ation Providers

六、Action Provider

Action Views 和 Ation Providers

七、DrawerLayout + NavigationView + Toolbar

概念熟悉之 DrawerLayout

Paste_Image.png

趕緊翻一翻 DrawerLayout Google文檔

DrawerLayout acts as a top-level container for window content that allows for interactive "drawer" views to be pulled out from one or both vertical edges of the window.

Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right (or start/end on platform versions that support layout direction.) Note that you can only have one drawer view for each vertical edge of the window. If your layout configures more than one drawer view per vertical edge of the window, an exception will be thrown at runtime.


To use a DrawerLayout, position your primary content view as the first child with width and height of match_parent and no layout_gravity>. Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.

DrawerLayout.DrawerListener can be used to monitor the state and motion of drawer views. Avoid performing expensive operations such as layout during animation as it can cause stuttering; try to perform expensive operations during the STATE_IDLE state. DrawerLayout.SimpleDrawerListener offers default/no-op implementations of each callback method.

DrawerLayout.DrawerListener這個接口可用來抽屜的開閉狀態和運動趨勢。


As per the Android Design guide, any drawers positioned to the left/start should always contain content for navigating around the application, whereas any drawers positioned to the right/end should always contain actions to take on the current content. This preserves the same navigation left, actions right structure present in the Action Bar and elsewhere.

For more information about how to use DrawerLayout, read Creating a Navigation Drawer.

Drawer是“抽屜”的意思。

  • DrawerLayout 是作為一個頁面(視窗)的頂層容器,它允許可以從頁面(視窗)的邊緣拉出。
  • 抽屜的子View通過android:layout_gravity屬性可以決定抽取的抽取方向,一般是向左或者向右,(如果平臺版本支持的話還可以上下抽出)。需要注意的是,每個頁面的抽屜只能有一個抽出方向,如果你配置了多個抽出方向,那么拋異常。
  • 使用DrawerLayout的時候,第一個子View可以作為在 主內容 View,主內容View高度一般為match_parent并且不設置layout_gravity,然后,我們需要在 主內容 View后面添加一個View作為 抽屜 View ,抽屜View可以通過layout_gravity屬性設置一個合適的抽出方向。抽屜View通常高度是match_parent ,而寬度是固定的。
  • NavigationView通常是作為DrawerLayout的子View和DrawerLayout配套使用的。

等等,NavigationView 又是什么??

概念熟悉之 NavigationView

NavigationView

Paste_Image.png

Google說:

Represents a standard navigation menu for application. The menu contents can be populated by a menu resource file.

NavigationView is typically placed inside a DrawerLayout.
  • NavigationView是一個標準的android程序的導航菜單。菜單的內容由xml布局文件進行填充。
  • NavigationView通常是放置在DrawerLayout的內部。

大概兩者就是這么合作的

<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"
     android:fitsSystemWindows="true">

     <!-- Your contents -->

     <android.support.design.widget.NavigationView
         android:id="@+id/navigation"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:menu="@menu/my_navigation_items" />
 </android.support.v4.widget.DrawerLayout>

來代碼

1、配置布局文件

<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"
    android:fitsSystemWindows="true">

    <!--Coordinator 協調  做伸縮-->
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> 
        </android.support.design.widget.AppBarLayout>
        <FrameLayout
            android:id="@+id/frame_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/appbar"
            android:scrollbars="none"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    </android.support.design.widget.CoordinatorLayout>

    <!--導航菜單  設置 頭部 和 菜單-->
    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer"
        app:headerLayout="@layout/nav_header"
        />

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

這里面都沒什么特殊的,要注意的只是

        app:menu="@menu/drawer"
        app:headerLayout="@layout/nav_header"

這兩行代碼。

顧名思義,一個是菜單,menu,一個是頭部布局,headerLayout

  • menu 必須,文件在menu文件夾配置

  • headerLayout 非必須,視需而定

  • 另外NavigationView layout_gravity這個屬性系統好像不會自動提示,需要手動敲上去

.
.
menu文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/navigation_person"
            android:icon="@mipmap/edit"
            android:title="個人設置" />
        <item
            android:id="@+id/navigation_item_intimity"
            android:icon="@mipmap/setting"
            android:title="隱私設置" />
        <item
            android:id="@+id/navigation_item_system"
            android:icon="@mipmap/share"
            android:title="系統設置 " />

        <item
            android:id="@+id/navigation_item_about"
            android:icon="@mipmap/sugar"
            android:title="關于" />
    </group>
</menu>

.
.
headerLayout nav_header

<?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"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="?attr/colorPrimaryDark"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">


    <ImageView
        android:id="@+id/profile_image"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:layout_marginTop="20dp"
        android:src="@mipmap/ic_launcher"
        />
    <TextView
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="APP DEV"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        />

</LinearLayout>

2、Activity

public class DrawerLayoutActivity  extends AppCompatActivity{

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private Toolbar mToolbar;

    private NavigationView mNavigationView;

    private static final int ANIM_DURATION_TOOLBAR = 300;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open,
                R.string.close);
        mDrawerToggle.syncState();
        mDrawerLayout.addDrawerListener(mDrawerToggle); // 給抽屜布局添加 導航 監聽
        
        // 導航部分開始
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

        // ====  導航頭
        View headerView1 = mNavigationView.getHeaderView(0);
        ImageView profileView = (ImageView) headerView1.findViewById(R.id.profile_image);
        if (profileView != null) {
            profileView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchToSystem();
                    mDrawerLayout.closeDrawers();
                    mNavigationView.getMenu().getItem(1).setChecked(true);
                }
            });
        }// ====  導航頭
        
        // 導航菜單
        mNavigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                            case R.id.navigation_person:
                                switchToPerson();
                                break;
                            case R.id.navigation_item_intimity:
                                switchToIntimity();
                                break;
                            case R.id.navigation_item_system:
                                switchToSystem();
                                break;
                            case R.id.navigation_item_about:
                                switchToAbout();
                                break;

                        }
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });

        // 導航部分結束

        switchToPerson();
    }


    private void switchToPerson() {
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new PersonFragment()).commit();
        mToolbar.setTitle("個人設置~");
    }

    private void switchToIntimity() {
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new IntimityFragment()).commit();
        mToolbar.setTitle("隱私設置~~");
    }

    private void switchToSystem() {
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new SystemFragment()).commit();
        mToolbar.setTitle("系統設置~~~");
    }
    private void switchToAbout() {
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new AboutFragment()).commit();
        mToolbar.setTitle("關于~~~~");
    }

}

3、fragment參考

PersonFragment

public class PersonFragment extends Fragment {

    private View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_person,null);
        return rootView;
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="個人設置"
        android:layout_centerInParent="true"
        />

</RelativeLayout>

效果展示:

抽屜導航.gif

本篇完。

MD系列1、RecyclerView良好參考
Md系列3、CoordinatorLayout 里 Toobar和TabLayout等發生的一系列故事

demo參考

參考:

更簡單更全的material design狀態欄

JuheNews系列之二 · ToolBar + AppBarLayout + CoordinatorLayout

ToolBar與AppcompatAcitivity實現浸入式Statusbar效果

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,511評論 0 17
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,513評論 2 45
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,242評論 25 708
  • 原文地址:http://www.android100.org/html/201606/06/241682.html...
    AFinalStone閱讀 983評論 0 1
  • 最近沒故事(買不買書) 我想了好久,腦子突然就冒出了一個這樣的題目,的確,如題,我最近沒有什么故事可寫,所以很無...
    阿驢閱讀 246評論 0 1