4

我正在测试材料设计,并且正在使用扩展工具栏开发应用程序。我的应用程序非常简单:主要活动扩展ActionBarActivity,我的布局如下所示:

<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"
    tools:context=".WeatherActivity"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/my_toolbar"
        android:layout_height="128dp"
        popupTheme="@style/ActionBarPopupThemeOverlay"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:text="@string/location_placeholder"
        android:textAlignment="viewStart"
        android:layout_gravity="start"
        />
</LinearLayout>

现在我想将当前位置显示为标题。我注意到的第一件事是在我的 Android Emulator (API 18) 中,标题似乎不遵守关于左边距下边距的材料指南,它出现在左侧并垂直输入到工具栏内。那么我应该使用工具栏标题(toolbar.setTitle)还是其他东西?其次,如果我想创建更复杂的内容,例如标题和简短描述(如布局结构中的材料指南所示),我的布局应该是什么?感谢您的支持!

4

1 回答 1

7

好的,您的活动扩展ActionBarActivity,因此您还必须确保此活动的主题是Theme.AppCompat.NoActionBaror的子项Theme.AppCompat.Light.NoActionBar。如果您不使用Theme.AppCompat变体,那么您也可以将以下几行添加到您的主题中:

<item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item> 

然后你需要做的就是将工具栏添加到你的布局中(看起来你已经有了):

<android.support.v7.widget.Toolbar
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_height="128dp"
    popupTheme="@style/ActionBarPopupThemeOverlay"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary" />

然后在您的活动中通过以下方式将工具栏设置为您的操作栏setSupportActionBar

    Toolbar mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(mToolbar);

最后一部分是所有魔法发生的地方,因为您说“Android,使用这个工具栏小部件,并完全按照您使用 SupportActionBar 的方式使用它”。这意味着如果你想设置标题/副标题,你需要做的就是调用:

    getSupportActionBar().setTitle("Toolbar Title");
    getSupportActionBar().setSubtitle("Toolbar Subtitle");

这也意味着您可以使用相同的回调在工具栏上创建菜单。

直接回答您的问题:

那么我应该使用工具栏标题(toolbar.setTitle)还是其他东西?

您实际上可以使用任何一个,toolbar.setTitle()或者getSupportActionBar().setTitle()

其次,如果我想创建更复杂的内容,例如标题和简短描述(如布局结构中的材料指南所示),我的布局应该是什么?

Toolbar 支持 Titles 和 Subtitles 所以你应该设置。我会查看文档以查看所有工具栏支持的内容。作为一般规则,如果操作栏可以做到,那么工具栏也可以。如果您有超出 Toolbar 支持的疯狂要求,请记住 Toolbar 只是一个精美的 ViewGroup,因此您可以像添加 LinearLayout 一样轻松添加小部件/视图。

于 2014-10-23T14:04:49.723 回答