一直以来,都只是听说过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:这个值使菜单和它的图标,菜单文本一起显示。