一直以來,都只是聽說過actionbar這個東西,僅僅知道這是一個標題頭,然而對我來說我可以花費點功夫自己寫一個通用的標題頭,基本上也可以滿足一般項目的基本需求,所以我也懶得去研究那個東西。然而在android5.0中,google推出了toolbar這個東西並且添加了很多交互在裏面,所以這個東西也是值得我們去學習一下的;今天我們就來看一看這個東西都是怎麼使用的
首先 在gradle中是需要引入下面這個庫的
compile 'com.android.support:appcompat-v7:22.2.0'
接下來是 主題
以上效果的主題配置如下:
1.colorPrimary: Toolbar導航欄的底色。
2.colorPrimaryDark:狀態欄的底色,注意這裏只支持Android5.0以上的手機。
3.textColorPrimary:整個當前Activity的字體的默認顏色。
4.android:windowBackground:當前Activity的窗體顏色。
5.colorAccent:CheckBox,RadioButton,SwitchCompat等控件的點擊選中顏色
6.colorControlNormal:CheckBox,RadioButton,SwitchCompat等默認狀態的顏色。
7.colorButtonNormal:默認狀態下Button按鈕的顏色。
8.editTextColor:默認EditView輸入框字體的顏色。
由於下面我們要研究主題,所以在style主題中我們定義三個樣式
並且在values-v21中也新建style文件
這是values文件夾內的style
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- 窗口的背景顏色 -->
<item name="android:windowBackground">@android:color/white</item>
<!-- SearchView -->
<item name="searchViewStyle">@style/MySearchViewStyle</item>
</style>
<style name="AppBaseTheme0" parent="AppBaseTheme">
<!-- toolbar(actionbar)顏色 -->
<item name="colorPrimary">#FF9800</item>
<!-- 狀態欄顏色 -->
<item name="colorPrimaryDark">#FF9800</item>
</style>
<style name="AppBaseTheme1" parent="AppBaseTheme">
<!-- toolbar(actionbar)顏色 -->
<item name="colorPrimary">#FF5722</item>
<!-- 狀態欄顏色 -->
<item name="colorPrimaryDark">#FF5722</item>
</style>
<style name="AppBaseTheme2" parent="AppBaseTheme">
<!-- toolbar(actionbar)顏色 -->
<item name="colorPrimary">#795548</item>
<!-- 狀態欄顏色 -->
<item name="colorPrimaryDark">#795548</item>
</style>
<style name="AppTheme0" parent="@style/AppBaseTheme0"></style>
<style name="AppTheme1" parent="@style/AppBaseTheme1"></style>
<style name="AppTheme2" parent="@style/AppBaseTheme2"></style>
<style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView">
<!--
Background for the search query section (e.g. EditText)
<item name="queryBackground">...</item>
Background for the actions section (e.g. voice, submit)
<item name="submitBackground">...</item>
Close button icon
<item name="closeIcon">...</item>
Search button icon
<item name="searchIcon">...</item>
Go/commit button icon
<item name="goIcon">...</item>
Voice search button icon
<item name="voiceIcon">...</item>
Commit icon shown in the query suggestion row
<item name="commitIcon">...</item>
Layout for query suggestion rows
<item name="suggestionRowLayout">...</item>
-->
</style>
</resources>
這是values-v21文件夾內的style
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppTheme0" parent="@style/AppBaseTheme0">
<!-- 底部導航欄顏色 -->
<item name="android:navigationBarColor">#FF9800</item>
</style>
<style name="AppTheme1" parent="@style/AppBaseTheme1">
<!-- 底部導航欄顏色 -->
<item name="android:navigationBarColor">#FF5722</item>
</style>
<style name="AppTheme2" parent="@style/AppBaseTheme2">
<!-- 底部導航欄顏色 -->
<item name="android:navigationBarColor">#795548</item>
</style>
</resources>
接下來發一下activity中的源碼
package com.my.toolbardemo;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainBaseActivity extends ToolBarBaseActivity implements View.OnClickListener{
private Button a;
private Button b;
private Button c;
@Override
protected void onCreate(Bundle savedInstanceState) {
Utils.onActivityCreateSetTheme(this);
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT&&Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
}
addView(R.layout.activity_main);
}
@Override
protected void initViews() {
a=(Button)findViewById(R.id.a);
b=(Button)findViewById(R.id.b);
c=(Button)findViewById(R.id.c);
a.setOnClickListener(this);
b.setOnClickListener(this);
c.setOnClickListener(this);
}
@Override
protected void initEvents() {}
@Override
protected void init() {}
@Override
public void onCreateCustomToolBar(View view,Toolbar toolbar) {
super.onCreateCustomToolBar(view, toolbar);
toolbar.showOverflowMenu();
toolbar.setNavigationIcon(R.mipmap.ic_launcher);
// getLayoutInflater().inflate(R.layout.toobar_button, toolbar);
// TextView btn = (TextView) toolbar.findViewById(R.id.id_txt_btn);
// btn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Toast.makeText(v.getContext(),"test",Toast.LENGTH_SHORT).show();
// }
// });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
// MenuItem itemCompat = menu.findItem(R.id.action_search);
// SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(itemCompat);
// mSearchView.setIconified(false);
// mSearchView.setIconifiedByDefault(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home) {
// Snackbar.make(view, "Snack Bar Text", Snackbar.LENGTH_LONG)
// .setAction("Go!", new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// }
// })
// .setActionTextColor(Color.BLUE).show();
//其中view是爲了尋找此view的父view,並顯示在其中
Snackbar.make(a, "Snack Bar Text", Snackbar.LENGTH_LONG).setActionTextColor(Color.BLUE).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.a:
Utils.changeToTheme(1);
this.finish();
this.startActivity(new Intent(this, this.getClass()));
break;
case R.id.b:
Utils.changeToTheme(2);
this.finish();
this.startActivity(new Intent(this, this.getClass()));
break;
case R.id.c:
Utils.changeToTheme(3);
this.finish();
this.startActivity(new Intent(this, this.getClass()));
break;
}
}
}
上述代碼做了適配,在4.4版本上會取消標題欄,然後設置toolbar的paddingTop爲25dp,具體的知識點請找上篇博客Android 透明(沉浸)狀態欄 各個版本的完全解決方案
並且其中使用了最新的Snackbar,裏面介紹了兩種實現方式,一種是最普通的提示,另一種能夠添加一個按鈕並且執行一定的操作,而且Snackbar一定要在CoordinatorLayout佈局中才能實現一些消失動畫;
package com.my.toolbardemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
public abstract class ToolBarBaseActivity extends AppCompatActivity {
public Toolbar toolbar ;/*視圖構造器*/
private LayoutInflater mInflater;
/*base view*/
private LinearLayout mContentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected abstract void initViews();
protected abstract void initEvents();
protected abstract void init();
/** 通過Id添加view,添加到linearLayout中 */
protected void addView(int layoutResID) {
mInflater = LayoutInflater.from(this);
setContentView(R.layout.base_activity);
mContentView=(LinearLayout)findViewById(R.id.ll_content);
mContentView.addView(mInflater.inflate(layoutResID, null),
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
toolbar = (Toolbar)findViewById(R.id.id_tool_bar);
/*自定義的一些操作*/
onCreateCustomToolBar(mContentView, toolbar) ;
/*把 toolbar 設置到Activity 中*/
setSupportActionBar(toolbar);
initViews();
initEvents();
init();
}
public void onCreateCustomToolBar(View view ,Toolbar toolbar){
toolbar.setContentInsetsRelative(0,0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
finish();
return true ;
}
return super.onOptionsItemSelected(item);
}
}
其中更換主題的時候,一定要在加載當前活動oncreat之前調用setTheme,才能生效
package com.my.toolbardemo;
import android.app.Activity;
public class Utils {
private static int sTheme = 1;
/**
* Set the theme of the Activity, and restart it by creating a new Activity
* of the same type.
*/
public static void changeToTheme(int theme)
{
sTheme = theme;
}
/** Set the theme of the activity, according to the configuration. */
public static void onActivityCreateSetTheme(Activity activity)
{
switch (sTheme)
{
default:
case 1:
activity.setTheme(R.style.AppTheme0);
break;
case 2:
activity.setTheme(R.style.AppTheme1);
break;
case 3:
activity.setTheme(R.style.AppTheme2);
break;
}
}
}
怎麼給menu的各個Item添加點擊事件呢?Toolbar給我們提供如下方法
Activity繼承Toolbar的OnMenuItemClickListener接口
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener
//實現接口
toolbar.setOnMenuItemClickListener(this);
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
Toast.makeText(this, 查找按鈕, Toast.LENGTH_SHORT).show();
break;
case R.id.action_share:
Toast.makeText(this, 分享按鈕, Toast.LENGTH_SHORT).show();
break;
}
return false;
}
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/a"
android:text="a"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
<Button
android:id="@+id/b"
android:text="b"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
<Button
android:id="@+id/c"
android:text="c"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"/>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/id_tool_bar"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:paddingTop="@dimen/toolbar_padding_top"
android:background="?attr/colorPrimary"
>
</android.support.v7.widget.Toolbar>
<LinearLayout
android:id="@+id/ll_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
這個xml是更改toolbar樣式的
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center"
android:text="toolBar"
android:textColor="@android:color/white"
android:textSize="18sp"
android:layout_marginRight="?attr/actionBarSize"
/>
<TextView
android:id="@+id/id_txt_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:gravity="center"
android:text="按鈕"/>
</RelativeLayout>
</RelativeLayout>
下面是menu的代碼
<?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=".MainBaseActivity" >
<item
android:id="@+id/ab_search"
android:orderInCategory="80"
android:title="action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/action_share"
android:orderInCategory="90"
android:title="action_share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="never"/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="action_settings"
app:showAsAction="never"/>
</menu>
單項屬性是android:showAsAction。 這個屬性可接受的值有:
1.alaways:這個值會使菜單項一直顯示在ActionBar上。
2.ifRoom:如果有足夠的空間,這個值會使菜單顯示在ActionBar上。
3.never:這個值菜單永遠不會出現在ActionBar是。
4.withText:這個值使菜單和它的圖標,菜單文本一起顯示。