Android 5.x theme: AppCompatActivity与toolbar的结合

来源:互联网 发布:js obj defaultvalue 编辑:程序博客网 时间:2024/05/16 05:49

1.概述

Android 5.x theme 是material design风格的主题。在API22之前我们使用标题栏基本都是在ActionBarActivity的Activity中处理的,而API22之后,谷歌遗弃了ActionBarActivity,推荐我们也可以说是强制我们使用AppCompatActivity。

编译版本和匹配的支持库:

  • compileSdkVersion 22
  • buildToolsVersion “22.0.1”
  • compile ‘com.android.support:appcompat-v7:22.1.1’
  • 忽然发现ActionBarActivity被弃用了,推荐使用AppCompatActivity,相关blog地址:Android Support Library 22.1
2.Material Design 风格的theme

md的主题有:

  • @android:style/Theme.Material (dark version)
  • @android:style/Theme.Material.Light (light version)
  • @android:style/Theme.Material.Light.DarkActionBar

与之对应的Compat Theme:

  • Theme.AppCompat
  • Theme.AppCompat.Light
  • Theme.AppCompat.Light.DarkActionBar
2.1 设置调色板

    <!-- 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>

  • colorPrimary 对应ActionBar的颜色。
  • colorPrimaryDark对应状态栏的颜色
  • colorAccent 对应EditText编辑时、RadioButton选中、CheckBox等选中时的颜色。
对应的图如下:


对于5.0以下的设备,目前colorPrimaryDark无法去个性化状态栏的颜色;

3. Toolbar的使用

在使用ActionBar的时候,一堆的问题:这个文字能不能定制,位置能不能改变,图标间距的控制,由此暴露出了ActionBar设计的不灵活。为此官方提供了ToolBar,并且提供了supprot library用于向下兼容。Toolbar之所以灵活,是因为它其实就是一个ViewGroup,我们在使用的时候和普通的组件一样,在布局文件中声明。

3.1 使用方法

(1)隐藏toolbar

我们知道在AndroidManifest.xml清单文件下application中设置了android:theme="@style/AppTheme"而查看AppTheme看到如下样式:

<resources>          <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">          </style>      </resources>  
从名字我们就可以看出来,默认的标题栏为黑色。我们使用了toolbar就必须修改样式文件,将原来的标题栏去掉,继承主题Theme.AppCompat.Light.NoActionBar修改后的样式文件如下:

    <style name="AppTheme" parent="AppTheme.Base">        </style>        <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">            <item name="colorPrimary">@color/colorPrimary</item>            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>            <item name="colorAccent">@color/colorAccent</item>       </style>  
实际上就是设置没有标题,无actionBar主题:

<style name="Theme.AppCompat.Light.NoActionBar">          <item name="windowActionBar">false</item>          <item name="windowNoTitle">true</item>  </style>
为了支持5.0的手机,需要建立一个文件夹values-v21,再新建style.xml文件,设置

<style name="AppTheme" parent="AppTheme.Base">  </style> 
(2)布局文件中申明

<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:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.jxf.themedemo.MainActivity">    <android.support.design.widget.AppBarLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:theme="@style/AppTheme.AppBarOverlay">        <android.support.v7.widget.Toolbar            android:id="@+id/toolbar"            android:layout_width="match_parent"            android:layout_height="?attr/actionBarSize"            app:title="main title"            app:subtitle="sub title"            app:navigationIcon="@mipmap/ic_launcher_round"            app:logo="@mipmap/ic_launcher"            android:background="?attr/colorPrimary"            />        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="悬停条目"/>    </android.support.design.widget.AppBarLayout>    <include layout="@layout/content_main" />    <android.support.design.widget.FloatingActionButton        android:id="@+id/fab"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="bottom|end"        android:layout_margin="@dimen/fab_margin"        app:srcCompat="@android:drawable/ic_dialog_email" /></android.support.design.widget.CoordinatorLayout>
(3)代码设定

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });    }
3.2  定制ToolBar

背景色:我们的ToolBar就是一个普通的ViewGroup在布局中,所以我们直接使用background就好,值可以为:?attr/colorPrimary使用主题中定义的值。

ToolBar中包含Nav Icon , Logo , Title , Sub Title , Menu Items


我们可以通过代码设置上述ToolBar中的控件:

@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.id_toolbar);        // App Logo        toolbar.setLogo(R.mipmap.ic_launcher);        // Title        toolbar.setTitle("App Title");        // Sub Title        toolbar.setSubtitle("Sub title");        setSupportActionBar(toolbar);        //Navigation Icon        toolbar.setNavigationIcon(R.drawable.ic_toc_white_24dp);    }
可选方案当然如果你喜欢,也可以在布局文件中去设置部分属性:

        <android.support.v7.widget.Toolbar            android:id="@+id/toolbar"            android:layout_width="match_parent"            android:layout_height="?attr/actionBarSize"            app:title="main title"            app:subtitle="sub title"            app:navigationIcon="@mipmap/ic_launcher_round"            app:logo="@mipmap/ic_launcher"            android:background="?attr/colorPrimary"            />
至于Menu Item,依然支持在menu/menu_main.xml去声明,然后复写onCreateOptionsMenuonOptionsItemSelected即可:

    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        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;        }        return super.onOptionsItemSelected(item);    }

可选方案也可以通过toolbar.setOnMenuItemClickListener实现点击MenuItem的回调:

  toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {            @Override            public boolean onMenuItemClick(MenuItem item) {                return false;            }        });
关于字体的样式,可以在布局文件设置属性app:titleTextAppearanceapp:subtitleTextAppearance或者代码setTitleTextAppearancesetSubTitleTextAppearance设置。

设置回退按钮:

假如我的这个界面并不是主界面,而是一个子界面,这个时候我有一个需求,需要回退到上一个界面那么怎么设置左边的图标并实现其方法。其实很简单,在setSupportActionBar(toolbar);后面加入如下代码:

toolbar.setNavigationIcon(R.drawable.back);toolbar.setNavigationOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        finish();    }});

Toolbar的菜单样式:

首先要说明一下,toolbar菜单默认样式的父类为Widget.AppCompat.Light.PopupMenu.Overflow,那么要更改toobar中菜单的弹出的样式,就必须继承这个父类的样式。

    <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">        <item name="colorPrimary">@color/material_blue_500</item>        <item name="colorPrimaryDark">@color/material_blue_700</item>        <item name="colorAccent">@color/material_green_A200</item>        <item name="android:windowBackground">@color/material_green_A200</item>        <item name="actionOverflowMenuStyle">@style/LYJMenuStyle</item>    </style>    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />    <style name="LYJMenuStyle" parent="@style/Widget.AppCompat.Light.PopupMenu.Overflow">        <item name="overlapAnchor">false</item>        <item name="android:popupBackground">?attr/colorPrimary</item>        <item name="android:dropDownVerticalOffset">0dip</item>    </style>

设置这一个属性那么其弹出的样式就与其他APP一样不会覆盖标题栏。

还有其他属性这里简要说明一下:

①<item name="android:popupBackground">?attr/colorPrimary</item>:弹出菜单背景色为标题栏的背景色

②<item name="android:dropDownVerticalOffset">0dip</item>:弹出菜单与标题栏的垂直间距

最后介绍一下菜单里面重要的几个属性:

app:showAsAction有三个值:

always:总是显示在界面上
never:不显示在界面上,只让出现在右边的三个点中
ifRoom:如果有位置才显示,不然就出现在右边的三个点中

可以用 | 同时使用两个上面的值。

系统也为菜单提供了默认的分享菜单与查询菜单,代码如下:

app:actionViewClass="android.support.v7.widget.SearchView"

app:actionProviderClass="android.support.v7.widget.ShareActionProvider"

android:orderInCategory数值越小,显示靠前,且优先级最大。
3.3 android.support.design.widget.AppBarLayout

AppBarLayout 是一个包含Toolbar的ViewGroup,  Toolbar和其它的view作为AppBarLayout的子View,AppBarLayout整体作为一个app Bar. 布局如下:

    <android.support.design.widget.AppBarLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:theme="@style/AppTheme.AppBarOverlay">        <android.support.v7.widget.Toolbar            android:id="@+id/toolbar"            android:layout_width="match_parent"            android:layout_height="?attr/actionBarSize"            app:title="main title"            app:subtitle="sub title"            app:navigationIcon="@mipmap/ic_launcher_round"            app:logo="@mipmap/ic_launcher"            android:background="?attr/colorPrimary"            />        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="悬停条目"/>    </android.support.design.widget.AppBarLayout>

3.4 自定义Toolbar

其实Toolbar是继承ViewGroup的一个容器控件,言外之意就是我们可以在Toolbar添加自己的布局了。

<android.support.v7.widget.Toolbar        android:id="@+id/toolbar"        android:layout_width="match_parent"        android:layout_height="?attr/actionBarSize"        android:background="?attr/colorPrimary">        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="center">            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="add" />            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_centerInParent="true"                android:layout_gravity="center_vertical"                android:text="标题"                android:textSize="18sp" />            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_alignParentRight="true"                android:background="@drawable/abc_ic_menu_share_mtrl_alpha" />        </RelativeLayout>    </android.support.v7.widget.Toolbar>
效果图:


这样我们就可以任意给Toolbar布局了。也解决了标题不能居中的问题。

4.Meterial Design主题风格Theme配置

除了Toolbar的风格,我们还可以通过设置Theme主题该控制Android很多控件的风格。直接上一张图片效果。


以上效果的主题配置如下:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        <!-- Customize your theme here. -->        <!--导航栏底色-->        <item name="colorPrimary">@color/accent_material_dark</item>        <!--状态栏底色-->        <item name="colorPrimaryDark">@color/accent_material_light</item>        <!--导航栏上的标题颜色-->        <item name="android:textColorPrimary">@android:color/black</item>        <!--Activity窗口的颜色-->        <item name="android:windowBackground">@color/material_blue_grey_800</item>        <!--按钮选中或者点击获得焦点后的颜色-->        <item name="colorAccent">#00ff00</item>        <!--和 colorAccent相反,正常状态下按钮的颜色-->        <item name="colorControlNormal">#ff0000</item>        <!--Button按钮正常状态颜色-->        <item name="colorButtonNormal">@color/accent_material_light</item>        <!--EditText 输入框中字体的颜色-->        <item name="editTextColor">@android:color/white</item>    </style>
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输入框字体的颜色。