工具栏是在应用程序布局中使用的操作栏的概括,现在回答您的问题有两种做法:
不良做法:
不好的做法是在每个布局中定义工具栏。
标准做法:
标准做法是定义布局并在基础活动中引用它。您只需要将此工具栏布局包含在您想要的任何布局中(通过使用<include>
)并在任何活动中扩展定义的基本活动。
此标准做法将帮助您为 Toolbar 保留一个代码库,并节省您每次定义 Toolbar 的时间。
示例:Google I/O 2014 安卓应用
toolbar_actionbar_with_headerbar.xml
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:iosched="http://schemas.android.com/apk/res-auto"
style="@style/HeaderBar"
iosched:theme="@style/ActionBarThemeOverlay"
iosched:popupTheme="@style/ActionBarPopupThemeOverlay"
android:id="@+id/toolbar_actionbar"
iosched:titleTextAppearance="@style/ActionBar.TitleText"
iosched:contentInsetStart="?actionBarInsetStart"
android:layout_width="match_parent"
android:layout_height="?actionBarSize" />
此工具栏布局在设置活动中引用,如下所示:
活动设置.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.SettingsActivity">
<include layout="@layout/toolbar_actionbar_with_headerbar" />
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>