前言
在 2014 年 Google IO 大会上,Google 推出了一套全新的设计规范 Material Design,这也为广大的 Android 开发者带来了福音,不用像以前一样照着 IOS 视觉稿来开发 Android APP,Material Design 的视觉风格本身就比较炫酷。
而 Google 也为我们提供符合 Material Design 风格的一系列组件,这大大的提高了我们的开发效率。由于 APP 改版在做 Material Design 化,所以后面会结合项目中的使用情况写几篇关于 Material Design 组件的文章,第一篇就从 Toolbar 开始吧。
一、ToolBar 介绍
Toolbar 是 Android5.0 中新引入的一个控件,其出现的目的就是为了取代 ActionBar。
而 Actionbar 在显示上应该算是应用 UI 的一部分,但是开发者又不能对其进行完全控制,因为它毕竟是由系统创建并对其进行相关参数的初始化。所以在实际开发中,很多开发者都是用布局生成一个模拟的 Actionbar 来代替系统的 Actionbar,基于这一点,Android 在 5.0 后推出一个新的控件 Toolbar 来取代 ActionBar。
二、ToolBar 属性
整理 Toolbar 比较常用的属性
1、toolbar:navigationIcon 设置 navigation button
2、toolbar:logo 设置 logo 图标
3、toolbar:title 设置标题
4、toolbar:titleTextColor 设置标题文字颜色
5、toolbar:subtitle 设置副标题
6、toolbar:subtitleTextColor 设置副标题文字颜色
7、toolbar:titleTextAppearance 设置 title text 相关属性,如:字体,颜色,大小等等
8、toolbar:subtitleTextAppearance 设置 subtitle text 相关属性,如:字体,颜色,大小等等
9、toolbar:logoDescription logo 描述
10、android:background Toolbar 背景
11、android:theme 主题
三、ToolBar 使用
本文是以最新的 androidx 环境下讲解,其实使用一模一样,就是包名有所变化。
-
使用 ToolBar 确保 Activity 继承的是 AppCompatActivity,
-
在应用清单中,将 application 元素设置为使用 appcompat 的其中一个 NoActionBar 主题。使用这些主题中的一个可以防止应用使用原生 ActionBar 类提供应用栏。
<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>
xml 布局文件中添加 Toolbar 控件
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:subtitleTextColor