浅谈ToolBar的基本用法

Google从Android5.0开始推进MaterialDesign规范,伴随着AppCompatActivity,ToolBar作为其典型的样例已经慢慢融入了众多开发者的怀抱。

下面逐步介绍ToolBar的各种玩法。
要使用ToolBar,为了兼容低版本我们要添加gradle依赖:

compile 'com.android.support:appcompat-v7:25.1.1'

首先,我们创建的每一个Activity默认都是使用了ActionBar的,那么为了使用ToolBar,我们就应该首先去掉默认的ActionBar。注意我们应该去掉ActionBar,这里使用requestWindowFeature(Window.FEATURE_NO_TITLE);是不可以的,程序运行之后仍然会报错:

   Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.                                               

我们这里在 res/values/styles.xml下编辑:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>


    <style name="AppTheme.Base" parent="Theme.AppCompat.Light">
        <item name="windowActionBar">false</item>
           <!--注意当我们使用API版本为22及以上来编译的时候要去掉前缀android:-->
        <item name="windowNoTitle">true</item>
    </style>
</resources>

通过上面的编辑我们就可以完成ToolBar的添加了,这也是最常用的做法。
当然我们也可以直接将AppTheme继承自系统已有的主题也能满足效果。

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>

需要注意的是,我们使用的主题都是带有Light的亮色主题,这对我们的ToolBar的属性定制有影响。

其次我们在布局文件中使用ToolBar:

  <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        >
    </android.support.v7.widget.Toolbar>

上面也是最基本的用法,需要说明的是,由于ToolBar是兼容版本库中的控件,其特有的属性需要使用app:前缀,我们首先应该在布局文件中声明其命名空间。
由于我们APP的整体风格是亮色主题,所以我们要指定ToolBar的主题为暗色调才能保证我们的Lable正确以亮色显示:

app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

同样的,弹出菜单默认和ToolBar一个风格,这将会与我们的App的风格不搭,我们需要强制指定其为亮色主题:

app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

ToolBar的颜色是我们在style的文件中指定的,对于MD风格颜色的设定,请参照我的另一篇博文:
http://blog.csdn.net/james_shu/article/details/54570919
此时在MainActivity中找到我们的控件然后就可以使用了:

        Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值