如何在工具栏中正确添加自定义视图?

How to properly add Custom View in toolbar?

我正在工具栏中添加一个自定义视图,但它没有使用整个工具栏宽度,它从左侧给出 space。

代码片段

<android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:background="@color/colorPrimary">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorAccent">

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

从此代码段获取视图

谁能告诉我为什么它没有使用全宽的工具栏?

在您的工具栏中添加这 4 个属性,它应该可以帮助您覆盖该效果

android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"  app:contentInsetLeft="0dp" app:contentInsetStart="0dp"

如果这对您有帮助,请告诉我。

实际上它只发生在 Android 版本 Lollipop 及更高版本上。要删除填充,您可以将内容插入设置为 0dp

将这些添加到您的工具栏

xmlns:app="http://schemas.android.com/apk/res-auto"
app:contentInsetStartWithNavigation="0dp"

这里已被报告为一个问题https://code.google.com/p/android/issues/detail?id=213826