本文出自 “阿敏其人” 簡(jiǎn)書(shū)博客扔仓,轉(zhuǎn)載或引用請(qǐng)注明出處。
一咖耘、Google口中的ToolBar
從Toolbar說(shuō)起
ToolBar->android.support.v7.widget.Toolbar
Toolbar是在Android 5.0以后推出來(lái)的翘簇,之前都是ActionBar這個(gè)控件
Google大概這么說(shuō)
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.
其實(shí)大概是這個(gè)意思
Toolbar 是一個(gè)應(yīng)用程序使用中的標(biāo)準(zhǔn)工具欄,Toolbar可以被嵌套在任意一個(gè)層級(jí)的View中鲤看。
相對(duì)ActionBar而言缘揪,Toolbar提供了更多牛逼的特性耍群。ToolBar是api21 新增的組件义桂,其主要用來(lái)彌補(bǔ)actionbar帶來(lái)的不足,其繼承自viewgroup蹈垢,自由的屬性包括:
- 導(dǎo)航按鈕(類似向上按鈕) (A navigation button)
- logo圖片 (A branded logo image.)
- 標(biāo)題和子標(biāo)題 (A title and subtitle)
- 一個(gè)或者多個(gè)自定義view (One or more custom views.)
- 菜單慷吊。 (An action menu.)
需要特別注意的是:我們可以在任何activity中使用toolbar作為actiobar,但是api21之前只能使用setSupportActionbar()曹抬,相應(yīng)的主題也要設(shè)置為NoActionbar.
二溉瓶、簡(jiǎn)單實(shí)用
最簡(jiǎn)單的使用
1、引入庫(kù)
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覺(jué)得不方便可以利用BaseActivity通知代碼設(shè)置一下,supportRequestWindowFeature(Window.FEATURE_NO_TITLE) )
4张足、布局實(shí)用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需要調(diào)用setSupportActionBar(ToolBar);方法,如果你的Activity是繼承自FragmentActivity为牍,是沒(méi)有這個(gè)方法的哼绑。
解決方案:將你的Activity改成繼承自AppCompatActivity,(AppCompatActivity是FragmentActivity的直接子類)
運(yùn)行效果:
是的現(xiàn)在看起來(lái)low且平凡碉咆,現(xiàn)在先放任不管抖韩,把一些陌生的東西集中處理一下:
問(wèn)題1、為什么style布局文件需要NoActionBar?
如果含有ActionBar疫铜,會(huì)和ToolBar沖突茂浮。所以必須在Style或者代碼指定,去掉ActionBar壳咕。
問(wèn)題2励稳、布局文件android:elevation="4dp" 是什么鬼?
android:elevation有海拔和立體的意思囱井,大概就是有一點(diǎn)浮動(dòng)的效果驹尼,更加美觀,不喜可刪庞呕。
material design 建議為app bar 的elevation設(shè)置為4dp新翎。
問(wèn)題3程帕、 指定ToolBar的主題: android:theme="@style/ThemeOverlay.AppCompat.ActionBar"和app:popupTheme="@style/ThemeOverlay.AppCompat.Light" 是什么鬼?
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"地啰,通過(guò)這句代碼愁拭,我們可以為不同頁(yè)面的ActionBar指定不同的主題樣式
app:popupTheme="@style/ThemeOverlay.AppCompat.Light",這鍋這句代碼亏吝,可以指定彈出的菜單的樣式
如果不加這兩句代碼岭埠,那么就是統(tǒng)一的默認(rèn)主題樣式。
詳情可以參考一下鏈接:
正確使用 Android 的 Theme 和 Style
android:theme和app:popupTheme的作用蔚鸥,以及在android 3.0以下不起作用問(wèn)題的解決
問(wèn)題4惜论、ToolBar的名字為何自帶標(biāo)題?
在運(yùn)行效果圖圖里面止喷,我們看到Toolbar有自帶的標(biāo)題馆类,這是因?yàn)槲覀傾ctivity里面調(diào)用了 setSupportActionBar(mToolBar);這句代碼。
當(dāng)我們 setSupportActionBar(mToolBar); 而又沒(méi)有指定標(biāo)題的時(shí)候弹谁,那么標(biāo)題就是程序名乾巧。
三、上吧预愤,五兄弟
我們之前說(shuō)過(guò)沟于,ToolBar可以包含
- 導(dǎo)航按鈕(類似向上按鈕) (A navigation button)
- logo圖片 (A branded logo image.)
- 標(biāo)題和子標(biāo)題 (A title and subtitle)
- 一個(gè)或者多個(gè)自定義view (One or more custom views.)
- 菜單。 (An action menu.)
那么現(xiàn)在我們來(lái)添加一下
先加三個(gè):
導(dǎo)航按鈕(類似向上按鈕) (A navigation button)
logo圖片 (A branded logo image.)
標(biāo)題和子標(biāo)題 (A title and subtitle)
mToolBar.setTitle("Title");
setSupportActionBar(mToolBar);
mToolBar.setNavigationIcon(R.mipmap.nac_icon);
mToolBar.setLogo(R.mipmap.sugar);
mToolBar.setSubtitle("SubTit");
導(dǎo)航按鈕植康,logo圖片旷太,沒(méi)什么提別的,
但是加標(biāo)題的時(shí)候向图,mToolBar.setTitle("Title");必須在setSupportActionBar(mToolBar);之前設(shè)置標(biāo)題才會(huì)生效
- 一個(gè)或者多個(gè)自定義view
ToolBar繼承自ViewGroup泳秀,所以是個(gè)容器,可以放置View
.
.
自定義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下創(chuàng)建菜單文件榄攀,(如果menu文件夾不在則創(chuàng)建之)
代碼
<?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="設(shè)置"
android:orderInCategory="90"
android:icon="@mipmap/menu_icon"
app:showAsAction="ifRoom" />
</menu>
showAsAction的值
app中有一個(gè)菜單(menu),showAsAction主要是針對(duì)這個(gè)菜單的顯示起作用的嗜傅,它有三個(gè)可選項(xiàng):
always:總是顯示在界面上
never:不顯示在界面上,只讓出現(xiàn)在右邊的三個(gè)點(diǎn)中
ifRoom:如果有位置才顯示檩赢,不然就出現(xiàn)在右邊的三個(gè)點(diǎn)中
.
.
創(chuàng)建關(guān)聯(lián)菜單
// 創(chuàng)建關(guān)聯(lián)菜單
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
.
.
菜單的點(diǎn)擊回調(diào)
// 菜單的點(diǎn)擊回調(diào)
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;
}
};
.
.
設(shè)置菜單點(diǎn)擊監(jiān)聽(tīng)
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");
// 設(shè)置菜單點(diǎn)擊監(jiān)聽(tīng)
mToolBar.setOnMenuItemClickListener(onMenuItemClick);
}
// 菜單的點(diǎn)擊回調(diào)
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;
}
};
// 創(chuàng)建關(guān)聯(lián)菜單
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
}
.
.
效果圖:
如果菜單項(xiàng)特別多,那么會(huì)在菜單的最右邊一向形成列表
<?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="設(shè)置"
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
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"
>
當(dāng)item圖標(biāo)較多棕洋,在Toolbar無(wú)法容下item,那么這時(shí)候Toolbar會(huì)在menu的最右邊生成一個(gè)菜單圖標(biāo)(三個(gè)豎直排列的小點(diǎn))乒融,有興趣可以改變menu文件嘗試一下掰盘。上面的代碼的我們自己也弄了一個(gè)一個(gè)豎直的三個(gè)小圖的菜單圖標(biāo)摄悯,兩者不是同一個(gè)東西,需要區(qū)分一下愧捕。
四杀饵、回退帶主頁(yè)
ToolBar可以生成一個(gè)回退按鈕酣藻,按下就回退到主頁(yè)
1、在清單文件對(duì)應(yīng)的activity添加對(duì)應(yīng)的meta-data售滤,鍵值的性質(zhì)最筒,指定主頁(yè)涧窒。
<?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設(shè)定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");
// 設(shè)置菜單點(diǎn)擊監(jiān)聽(tīng)
mToolBar.setOnMenuItemClickListener(onMenuItemClick);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
返回主頁(yè)效果圖
如果只想回退到上一頁(yè)
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
五棵里、 Action View
利用Action View,可以更好利用ToolBar的空間,比如ToolBar上面有一個(gè)搜索按鈕钢猛,平時(shí)是一個(gè)圖片伙菜,搜索時(shí)就變成一個(gè) 搜索欄 轩缤。
在Toolbar/Actionbar中添加SearchView實(shí)現(xiàn)搜索功能
Action Views 和 Ation Providers
六命迈、Action Provider
Action Views 和 Ation Providers
七、DrawerLayout + NavigationView + Toolbar
概念熟悉之 DrawerLayout
趕緊翻一翻 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這個(gè)接口可用來(lái)抽屜的開(kāi)閉狀態(tài)和運(yùn)動(dòng)趨勢(shì)火的。
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 是作為一個(gè)頁(yè)面(視窗)的頂層容器,它允許可以從頁(yè)面(視窗)的邊緣拉出馏鹤。
- 抽屜的子View通過(guò)
android:layout_gravity
屬性可以決定抽取的抽取方向征椒,一般是向左或者向右,(如果平臺(tái)版本支持的話還可以上下抽出)湃累。需要注意的是勃救,每個(gè)頁(yè)面的抽屜只能有一個(gè)抽出方向,如果你配置了多個(gè)抽出方向治力,那么拋異常蒙秒。 - 使用DrawerLayout的時(shí)候,第一個(gè)子View可以作為在 主內(nèi)容 View宵统,主內(nèi)容View高度一般為match_parent并且不設(shè)置layout_gravity晕讲,然后,我們需要在 主內(nèi)容 View后面添加一個(gè)View作為
抽屜
View 马澈,抽屜View可以通過(guò)layout_gravity屬性設(shè)置一個(gè)合適的抽出方向瓢省。抽屜View通常高度是match_parent ,而寬度是固定的痊班。 - NavigationView通常是作為DrawerLayout的子View和DrawerLayout配套使用的勤婚。
等等,NavigationView 又是什么涤伐?馒胆?
概念熟悉之 NavigationView
Google說(shuō):
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是一個(gè)標(biāo)準(zhǔn)的android程序的導(dǎo)航菜單荆永。菜單的內(nèi)容由xml布局文件進(jìn)行填充。
- NavigationView通常是放置在DrawerLayout的內(nèi)部国章。
大概兩者就是這么合作的
<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>
來(lái)代碼
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 協(xié)調(diào) 做伸縮-->
<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>
<!--導(dǎo)航菜單 設(shè)置 頭部 和 菜單-->
<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>
這里面都沒(méi)什么特殊的,要注意的只是
app:menu="@menu/drawer"
app:headerLayout="@layout/nav_header"
這兩行代碼液兽。
顧名思義骂删,一個(gè)是菜單,menu四啰,一個(gè)是頭部布局宁玫,headerLayout
menu 必須,文件在menu文件夾配置
headerLayout 非必須柑晒,視需而定
另外NavigationView layout_gravity這個(gè)屬性系統(tǒng)好像不會(huì)自動(dòng)提示欧瘪,需要手動(dòng)敲上去
.
.
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="個(gè)人設(shè)置" />
<item
android:id="@+id/navigation_item_intimity"
android:icon="@mipmap/setting"
android:title="隱私設(shè)置" />
<item
android:id="@+id/navigation_item_system"
android:icon="@mipmap/share"
android:title="系統(tǒng)設(shè)置 " />
<item
android:id="@+id/navigation_item_about"
android:icon="@mipmap/sugar"
android:title="關(guān)于" />
</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); // 給抽屜布局添加 導(dǎo)航 監(jiān)聽(tīng)
// 導(dǎo)航部分開(kāi)始
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
// ==== 導(dǎo)航頭
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);
}
});
}// ==== 導(dǎo)航頭
// 導(dǎo)航菜單
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;
}
});
// 導(dǎo)航部分結(jié)束
switchToPerson();
}
private void switchToPerson() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new PersonFragment()).commit();
mToolbar.setTitle("個(gè)人設(shè)置~");
}
private void switchToIntimity() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new IntimityFragment()).commit();
mToolbar.setTitle("隱私設(shè)置~~");
}
private void switchToSystem() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new SystemFragment()).commit();
mToolbar.setTitle("系統(tǒng)設(shè)置~~~");
}
private void switchToAbout() {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_content, new AboutFragment()).commit();
mToolbar.setTitle("關(guān)于~~~~");
}
}
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="個(gè)人設(shè)置"
android:layout_centerInParent="true"
/>
</RelativeLayout>
效果展示:
本篇完佛掖。
MD系列1、RecyclerView良好參考
Md系列3涌庭、CoordinatorLayout 里 Toobar和TabLayout等發(fā)生的一系列故事
參考:
更簡(jiǎn)單更全的material design狀態(tài)欄