我在哪里为Android 5.0中的工具栏小部件定义XML?

was*_*dhu 8 android android-layout android-5.0-lollipop android-toolbar

好的,我现在已经经历了几个StackOverflow帖子,但我仍然对我工具栏的xml的位置感到困惑.

<android.support.v7.widget.Toolbar
android:id=”@+id/my_awesome_toolbar”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:background=”@styles/colorPrimary” />
Run Code Online (Sandbox Code Playgroud)

它会进入我的/layout/activity_main.xml吗?

Par*_*ani 26

工具栏是在应用程序布局中使用的Action栏的概括,现在回答您的问题有两种做法:

不好的做法:

不好的做法是在每个布局中定义工具栏.

标准做法:

标准做法是定义布局并在基本活动中引用它.您只需要将此工具栏布局包含在您想要的任何布局中(通过使用<include>),并在任何活动中扩展已定义的基本活动.

此标准练习将帮助您为工具栏保留单个代码库,并节省您每次定义工具栏的时间.

示例: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" />
Run Code Online (Sandbox Code Playgroud)

此工具栏布局在设置活动中引用,如下所示:

activity_settings.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>
Run Code Online (Sandbox Code Playgroud)

  • 有用且信息量很大的答案.谢谢你帮我理解这个! (2认同)