Android ToolBar學習筆記
阿新 • • 發佈:2018-11-17
前言
開發中經常遇到頂部導航欄的需求,5.0 之後Google為了統一設計風格,默認了ToolBar這個控制元件作為統一頂部欄,並且還支援了不少的動畫和各種設定,但是!有關ToolBar 的theme,Menu,click有不少的坑,今天來系統的學習一下。
內容
基於需求來學習。頂部欄通常作用主要是顯示標題,回退按鈕,多一點的會有副標題,搜尋按鈕
基礎使用
先來看下初始的狀態
我們來新增背景和一些文字試試
顯示標題
修改ToolBar標題顏色、字號
1 在xml裡面控制
<android.support.v7.widget.Toolbar
android:id="@+ id/m_tool_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:subtitle="副標題"
app:title="標題"
android:theme="@style/tool_bar_style"
app:subtitleTextColor="@android:color/white" //修改副標題顏色
app:navigationIcon="@drawable/ic_arrow_back_black_24dp"
app:titleTextAppearance="?android:textAppearanceLarge" //修改標題文字樣式
app:titleTextColor="@android:color/white" /> //修改標題顏色
2 通過Theme設定
<android.support.v7.widget.Toolbar
android:id="@+id/m_tool_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:subtitle="副標題"
app:title="標題"
android:theme="@style/tool_bar_style"/>
<style name="tool_bar_style" parent="@style/ThemeOverlay.AppCompat.ActionBar">
<item name="titleTextColor">#0094ff</item><!--標題顏色-->
<item name="actionMenuTextColor">#000000</item><!--選單顏色-->
<item name="android:textSize">18sp</item><!--選單字型大小-->
</style>
如果都設定了還是以XML中設定的為主,因為style初始化的在設定熟悉之前。
Toolbar標題居中
這個不能用屬性了,只能自己寫佈局,注意ToorBar也是一個ViewGroup!
ToolBar 可以用在任意地方,如圖兩個Toolbar
<android.support.v7.widget.Toolbar
android:layout_marginTop="10dp"
app:title="第二個!"
android:theme="@style/tool_bar_style"
android:background="@color/cardview_dark_background"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textColor="@android:color/white"
android:layout_centerInParent="true"
android:text="居中的標題"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
可以看到你再ToolBar 設定的app:title 無效了,你可以理解為被遮蓋住了。
回退、搜尋、選單點選
生成選單
/*
* @return You must return true for the menu to be displayed;
* if you return false it will not be shown.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toor_bar_demo, menu);
return true;
}
注意ShowAsAction的幾個屬性,並且有圖示會優先顯示圖示
<!--
showAsAction有這幾大屬性(app名稱空間與android名稱空間顯示有些不同
ifRoom 會顯示在Item中,但是如果已經有4個或者4個以上的Item時會隱藏在溢位列表中。當然個數並不僅僅侷限於4個,依據螢幕的寬窄而定
never 永遠不會顯示。只會在溢位列表中顯示,而且只顯示標題,所以在定義item的時候,最好把標題都帶上。
always 無論是否溢位,總會顯示。
withText withText值示意Action bar要顯示文字標題。Action bar會盡可能的顯示這個標題,但是,如果圖示有效並且受到Action bar空間的限制,文字標題有可能顯示不全。
collapseActionView 聲明瞭這個操作視窗應該被摺疊到一個按鈕中,當用戶選擇這個按鈕時,這個操作視窗展開。否則,這個操作視窗在預設的情況下是可見的,並且即便在用於不適用的時候,也要佔據操作欄的有效空間。
-->
自定義佈局
能自定義的東西靈活度就很高,上面講過了其實就是在ToolBar裡面在嵌一個佈局,因為ToolBar就是一個ViewGroup。
總結
用一個例子來總結下,結合下側滑選單,CoordinatorLayout,先看效果。
側滑用的是DrawerLayout、NavigationView
主佈局視察效果用的CoordinatorLayout、CollapsingToolbarLayout
toast 用的SnackBar