Android工具栏的标题对齐问题

时间:2015-07-31 11:21:39

标签: android-layout android-toolbar

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

我想将工具栏的标题与中心对齐。但我意识到没有内置的方法可以让你这样做。

所以我在工具栏中添加了一个textview,如下所示 -

        <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本身并未覆盖屏幕的宽度。输出如下:

enter image description here

有关如何解决此问题的任何建议?

谢谢!

2 个答案:

答案 0 :(得分:0)

只需添加与主图标具有相同宽度的边距。我想

android:layout_marginRight="56dp"

应该恰到好处。

答案 1 :(得分:-1)

添加您自己的文本视图,可以根据需要对齐:

<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"/>

相关问题