Android 工具栏的标题对齐问题

Title alignment issue for Android Toolbar

我是第一次使用工具栏。我在我的应用程序中将它用作 Actionbar。

我想将工具栏的标题居中对齐。但我意识到没有 in-built 方法可以让你这样做。

所以我在工具栏中添加了一个文本视图,如下所示-

        <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#2196F3"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            **android:gravity="center"**
            android:id="@+id/txtTitle"
            android:textColor="@android:color/white"
            android:text="My Title" />
    </android.support.v7.widget.Toolbar>

然而,即使这种方法也不起作用,因为我的工具栏的左边缘包含一个抽屉菜单图标。因此,尽管我的文本在 textview 中居中对齐,但 Textview 本身并没有覆盖屏幕的宽度。输出结果如下:

关于如何解决这个问题有什么建议吗?

谢谢!

只需添加与主页图标宽度相同的边距即可。我猜

android:layout_marginRight="56dp"

应该刚刚好。

添加您自己的文本视图,它可以在您想要的任何位置对齐:

<android.support.v7.widget.Toolbar
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/toolbar"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/green">
 <TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:textColor="@android:color/white"
 android:text="My Title"
 android:textStyle="bold"/>