一、为什么要使用Toolbar
从 Android 3.0(API 级别 11)开始,所有使用默认主题的 Activity 均使用 ActionBar 作为应用栏。
不过,经过不同 Android 版本的演化,应用栏功能已逐渐添加到原生 ActionBar 中。
因此,原生 ActionBar 的行为会随设备使用的 Android 系统的版本而发生变化。
相比之下,最新功能已添加到支持库版本的 Toolbar 中,并且这些功能可以在任何能够使用该支持库的设备上使用。
因此,您应使用支持库的 Toolbar 类来实现 Activity 的应用栏。
使用支持库的工具栏有助于确保您的应用在最大范围的设备上保持一致的行为。
二、如何使用Toolbar
(1)确保你的Activity继承了AppCompatActivity
(2)在应用清单中,将 <application> 元素设置为使用 appcompat 的其中一个 NoActionBar 主题。使用这些主题中的一个可以防止应用使用原生 ActionBar 类提供应用栏。
例如:
<application
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
/>
(3)
向 Activity 的布局添加一个
Toolbar
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
(4)
在 Activity 的
onCreate()
方法中,调用 Activity 的
setSupportActionBar()
方法,然后传递 Activity 的工具栏。该方法会将工具栏设置为 Activity 的应用栏。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
现在你的的应用现在具有一个基本操作栏。默认情况下,操作栏只包含应用的名称和一个溢出菜单。
注意!Toolbar是作为一个UI组件存在的,在你的布局中不要让Toolbar覆盖了你的组件,你的组件应当在Toolbar的下方
<RelativeLayout 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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startActivity2"
<!--如果不设置这个属性,Button就会被Toolbar覆盖而无法显示-->
android:layout_below="@id/my_toolbar"
android:text="StartActivity"
android:id="@+id/button"/>
</RelativeLayout>