如何将工具栏标题居中显示(即使显示了工具栏返回按钮)

14
如何使活动标题在工具栏中居中,并且能够与工具栏的返回按钮一起使用?
目前,我找到的最佳解决方案是:如果显示返回按钮,则增加60dp的边距。

我认为你需要为你的操作栏创建一个自定义视图。 - Hussein El Feky
我尝试使用layout_gravity设置为center在工具栏视图中添加一个TextView。但是当工具栏返回按钮显示时,它不起作用。 - Jacques Giraudel
您可以创建一个自定义视图(包含一个按钮(返回)和一个文本视图(标题)的水平线性布局),并将它们居中显示。 - Hussein El Feky
相信我,设置边距不是最好的解决方案。在工具栏中添加自定义布局,并将其重心设置为中心。 - Mangesh
2个回答

5
只使用后退按钮时,这对我有效。在xml中:
<android.support.v7.widget.Toolbar
    android:id="@+id/tb_title_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textAllCaps="true"
        android:textColor="#2B2B2B"
        android:textSize="14sp" />

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

在 Java 代码中:
int contentInsetStartWithNavigation = mTitleContainer.getContentInsetStartWithNavigation();
mTitleContainer.setContentInsetsRelative(0, contentInsetStartWithNavigation);

1

我不知道最佳实践是什么,但你可以尝试使用工具栏内的自定义返回按钮来解决问题。布局代码如下:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/toolbar_back_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:src="@drawable/ic_back" />

        <TextView
            android:id="@+id/toolbar_title"
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center" />

    </RelativeLayout>

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

以及活动中的代码:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);

    ImageView backButton = (ImageView) findViewById(R.id.toolbar_back_button);
    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           finish();
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接