Android 工具栏(作为小部件)未显示标题

Android Toolbar (as widget) not showing title

我正在使用 Toolbar 作为底部 sheet 的小部件。但是标题没有显示。

我的Toolbar底部内容sheet布局是这样的:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:title="This is my title"
            app:theme="@style/ThemeOverlay.AppCompat.Light"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:onClick="@{() -> handler.hideBottomSheet()}"
                android:src="@drawable/ic_keyboard_arrow_down_black_24dp" />

        </android.support.v7.widget.Toolbar>

    //...

</LinearLayout>

一切看起来都很好。但标题不只是出现。这不是支持ActionBar。我将其用作小部件。

不知道为什么,就是不显示。我尝试了不同的主题并更改了根 LinearLayout 的背景颜色,但没有成功。

只是没有出现。我也试过设置 android:titleTextColor 但这也没有用。

title只能在as ActionBar时使用吗?或者我在这里做错了什么?谢谢。

试试这个代码

mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("");
setSupportActionBar(mActionBarToolbar);

现在您可以设置标题了

mActionBarToolbar.setTitle(title);

如文档中所述

Using XML attributes from the support library

Notice that the showAsAction attribute above uses a custom namespace defined in the tag. This is necessary when using any XML attributes defined by the support library, because these attributes do not exist in the Android framework on older devices. So you must use your own namespace as a prefix for all attributes defined by the support library.

您需要为此使用自定义前缀。所以使用 app:title 代替 android:title 如下。

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    app:title="This is my title"
    app:theme="@style/ThemeOverlay.AppCompat.Light"
    app:popupTheme="@style/AppTheme.PopupOverlay">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:onClick="@{() -> handler.hideBottomSheet()}"
        android:src="@drawable/ic_keyboard_arrow_down_black_24dp" />

</android.support.v7.widget.Toolbar>

Can title only used when using as ActionBar?

没有必要。您可以得到 toolbar name 而无需将其设置为 actionbar