為什么要使用ToolBar
在ToolBar還沒出現之前,因為ActionBar并不是那么好用一直都沒用用過,現在ActionBar已經過時了,Material Desgin 風格的ToolBar 在視覺動畫處理上很完美的和其他一些布局設計相融合,很方便的實現了ToolBar下滑隱藏上滑顯示的功能,動畫效果非常流暢,還能通過設置可以點擊打開Sliding Drawer,符合app設計原則和用戶操作習慣。下面我們開始一步步學習ToolBar的基本實現和一些細節設置。
添加一個帶有選項菜單的ToolBar
(1) 新建一個空項目
新建一個項目名稱為MaterialTest的新項目,在/app/src/main/res/values/style.xml文件中定義Material風格的主題樣式AppTheme(如果沒有的話)。并且讓AppTheme繼承 Theme.AppCompat.Light.NoActionBar:
<resources>
<!-- Base application theme.
parent="Theme.AppCompat.Light.NoActionBar"-->
<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>
在AndroidManifest.xml文件的<application/>中的theme屬性設置成AppTheme
android:theme="@style/AppTheme"
定制配色,這里我重新定制了自己想要的主題顏色
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#F9F9F9</color>
<color name="colorPrimaryDark">#999999</color>
<color name="colorAccent">#FF4081</color>
</resources>
(2) 添加ToolBar控件
在activity_main.xml中去掉根節點中默認設置的padding值和里面默認的顯示“Hello World!”的TextView控件
然后在里面添加<android.support.v7.widget.Toolbar/>控件
在<android.support.v7.widget.Toolbar/>外層需要用<android.support.design.widget.AppBarLayout/>包裹才會有Material 投影的效果,添加這個需要在app的build.gradle中加入如下依賴包:
compile 'com.android.support:design:25.1.0'
activity_main.xml中的完整代碼如下所示:
<?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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.enid.myapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
</android.support.design.widget.AppBarLayout>
</RelativeLayout>
這里來介紹一個小的知識點:
從上面的代碼中可以看到在設置height和background屬性的時候用到了?attr/actionBarSize和?attr/colorPrimary而不是平常用到的@dimen/ 和 @color/。這樣做的結果是,設置的高度和顏色是和設置的theme保持一致,隨設置的theme變化而變化,前提是theme中定義了相對應的屬性
Ctrl+Click 點擊可以看到在values.xml文件里面有這樣格式的定義:<declare-styleable>
<attr format= "" name = ""/>
</declare-styleable>
我們也可以自己聲明一個屬性實現這樣的效果,在一個attrs.xml/values.xml/style.xml任意一個文件的根目錄下定義如下:
<declare-styleable name="ColorAttr" format="reference"> <attr name="attrTestColor" format="reference"/> </declare-styleable>
在主題樣式中添加該屬性
<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="attrTestColor">@color/colorPrimaryDark</item>** </style>
在需要的地方添加屬性
android:background=**"?attr/attrTestColor" **
這樣arrtTestColor的顏色就隨著主題樣式里設置的顏色改變了(即上面紅色代碼處指定的顏色。
好了,回歸ToolBar的使用
最后在MainActivity添加如下代碼:
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
到現在ToolBar就添加好了,現在這個ToolBar只有一個標題如下圖所示:
(3) 給ToolBar添加選項菜單
在/app/src/main/res/menu/ 下新建main_menu.xml 菜單布局:
<?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">
<item
android:id="@+id/add_item"
android:icon="@drawable/toolbar_add"
android:title="Add"
app:showAsAction="always" />
<item
android:id="@+id/remove_item"
android:icon="@drawable/toolbar_delete"
android:title="Remove"
app:showAsAction="ifRoom" />
<item
android:id="@+id/filter_item"
android:icon="@drawable/toolbar_filter"
android:title="Update"
app:showAsAction="never" />
</menu>
app:showAsAction有三個選擇值:
always 總是顯示在ToolBar上
ifRoom 屏幕有足夠空間時顯示出來
never 總是隱藏在右側三個小圓點中
icon和title的設置,如果顯示在ToolBar上則只顯示icon不顯示title,如果隱藏在小圓點的按鈕中則只顯示title不顯示
在MainActivity中重寫 onCreateOptionsMenu()方法,創建菜單
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu);
return true;
}
重寫onOptionsItemSelected()方法,處理菜單選中事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_item:
toastMsg("click item Add");
break;
case R.id.remove_item:
toastMsg("click item Remove");
break;
case R.id.filter_item:
toastMsg("click item filter");
break;
default:
break;
}
return true;
}
完成后的效果如下所示
由于系統用的是淺色主題,ToolBar也將默認使用系統的所使用的主題,再添加了菜單選項后,Toolbar上的默認圖標和副標題是深色(灰色),Title是深色(黑色)
可以通過設置將Toolbar上默認圖標的顏色設置為深色(黑色)
這里我們設置Toolbar控件的屬性android:theme="@style/ThemeOverlay.AppCompat.ActionBar" 是將Toolbar設置為淺色主題,可以看到系統的三個小圓點變成深色(黑色)
若設置屬性android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"則是將ToolBar設置為深色主題,Toolbar上的文字圖標都將變成淺色(白色)
為了突出對比我們將Toolbar控件設置app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" 將Toolbar上彈出的popupWindow的主題設為深色,其上面文字將顯示為淺色
如果有特殊需求,Title、subTitle的顏色也可以自己通過相應屬性設置。
設置主題屬性后的效果:
(4)修改ToolBar標題
ToolBar的標題默認是AndroidManifest文件中<Application/>標簽下屬性label設置的值。可以通過toolbar.setTitle("Fruit");需要注意的是要在onCreate()方法完成以后設置否則還是會使用默認標題。我們可以重寫onPostCreate()方法設置標題:
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//set tool bar title
toolbar.setTitle("Fruit");
//set sub title
toolbar.setSubtitle("are favorite fruit");
}
TooBar隱藏、顯示動畫的實現
有很多應用都實現了這種效果:在界面顯示內容超出屏幕往下滑動時,頂部工具欄(菜單欄)自動隱藏,往上滑動時又顯示出來的效果。
(1) 使用RecyclerView和CardView填充界面內容
我們的項目中是在MainActivity中放置一個ViewPager,用Fragment填充ViewPager,在Fragment中使用RecyclerView + CardView 填充內容使內容超出屏幕大小,這里用到ViewPager是因為后面會講到TabLayout和ViewPager的結合使用效果。
在項目中用到了兩個依賴包:
compile 'com.android.support:cardview-v7:25.1.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
因為這篇文章主要講ToolBar的應用,所以這里不詳細列出RecyclerView和CardView的實現過程,這里說一點CardView需要注意的地方。
fruit_item.xml中<android.support.v7.widget.CardView/>標簽設置屬性app:cardUseCompatPadding="true",否則在有些手機中CardView之間沒有間隔:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
app:cardUseCompatPadding="true"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="match_parent"
android:layout_height="100dp"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
</LinearLayout>
</android.support.v7.widget.CardView>
之前在看郭林的《第一行代碼》第二版中學習Material Design時自己在網上找了一些水果圖片使用到項目中。
(2) 給ToolBar添加隱藏、顯示動畫
把根布局換成<android.support.design.widget.CoordinatorLayout/>標簽
在<android.support.v7.widget.Toolbar/>標簽中加入屬性app:layout_scrollFlags="scroll|enterAlways|snap"
在<android.support.v4.view.ViewPager/>標簽中加入屬性 app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layout_scrollFlags屬性是控制ToolBar的動畫,app:layout_behavior屬性是控制在滑動時ViewPager的滑動與ToolBar動畫的一致性
完整代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:background="?attr/attrTestColor"
android:layout_height="match_parent"
tools:context="com.enid.materialtest.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<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.ActionBar"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
完成后效果如下所示所示:
簡單介紹SwipeRefreshLayout、 FloagtingActionButton、 Snackbar的使用
在項目中常常要用的<android.support.v4.widget.SwipeRefreshLayout/>和<android.support.design.widget.FloatingActionButton/>這兩個控件。
- SwipeRefreshLayout的使用:
在frag_fruit.xml文件中用SwipeRefreshLayout將RecyclerView包裹起來,在MainActivity中通過findViewId方法獲取到控件
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.cardview_dark_background);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshFruits();
}
});
- FloatingActionButton的使用:
將FloatingActionButton放在CoordinatorLayout控件里面,一些關鍵的屬性設置如下:
android:layout_gravity="bottom|end"http://設置FloatingActionButton的位置
android:layout_margin="16dp" //FloatingActionButton 距離邊界的距離
android:src="@drawable/icon_share" //FloatingActionButton上顯示的圖標
app:elevation="8dp" //FloatingActionButton的高度位置,與投影的大小有關
在代碼中設置點擊點擊監聽給出一個提示,這里我們可以用Snackbar代替以前的Toast,Snackbar的使用方法和Toast差不多,顯示效果是一個長條,還可以多添加一個用戶操作處理
//FloatingActionButton & Snack bar
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "share data to someone", Snackbar.LENGTH_SHORT)
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
toastMsg("share canceled"); //在提示顯示時,用戶點擊事件處理
}
})
.show();
}
});
完成后效果如下所示:
總結
在上篇文章中,我們初步學習理解了什么是Material Desing 和Material Design 能帶給我們的作用效果,這篇文章主要學習了ToolBar的使用,了解了android:background="?attr/attrTestColor" 和 android:background="@color//attrTestColor" 的區別,以及SwipeRefreshLayout、FloatingActionButton、SnackBar的基礎用法,這些簡單的控件能給我們帶來十分美觀、友好的視覺體驗,下一篇文章中會進一步學習Navigation Drawer的使用。