目录
12.2 Toolbar
Toolbar 将会是我们本章接触的第一个控件,是由 AndroidX库提供的。虽说对于 Toolbar 你暂时应该还是比较陌生的,但是对于它的另一个相关控件 ActionBar ,你就应该有点熟悉了。
回忆一下,我们曾经在4.4.1 小节为了使用一个自定义的标题栏,而隐藏了系统原生的 ActionBar 。没错,每个 Activity 最顶部的那个标题栏其实就是 ActionBar ,之前我们编写的所有程序里一直都有它的身影。
不过 ActionBar 由于其设计的原因,被限定只能位于 Activity 的顶部,从而不能实现一些 Material Design 的效果,因此官方现在已经不再建议使用 ActionBar 了。那么本书中我也就不准备再介绍 ActionBar 的用法了,而是直接讲解现在更加推荐使用的 Toolbar 。
Toolbar 的强大之处在于,它不仅继承了ActionBar 的所有功能,而且灵活性很高,可以配合其他控件完成一些 Material Design 的效果,下面我们就来具体学习一下。
首先你要知道,任何一个新建的项目,默认都是会显示 ActionBar 的,这个想必你已经见识过太多次了。那么这个 ActionBar 到底是从哪里来的呢?其实这是根据项目中指定的主题来显示的。 打开 AndroidManifest.xml 文件看一下,如下所示:
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MaterialTes"
tools:targetApi="31">
...
</application>
可以看到,这里使用 android:theme 属性指定了一个Theme.MaterialTes 的主题。那么这个 AppTheme 又是在哪里定义的呢?打开res/values/themes.xml 文件,代码如下所示:
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MaterialTes" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
这里定义了一个叫 Theme.MaterialTes 的主题,然后指定它的 parent 主题是 Theme.MaterialComponents.DayNight.DarkActionBar 。这个 DarkActionBar 是一个深色的ActionBar 主题,我们之前所有的项目中自带的 ActionBar 就是因为指定了这个主题才出现的。
而现在我们准备使