当活动添加到后台堆栈时,如何将Android AppCompat工具栏中的文本居中?

当活动添加到后台堆栈时,如何将Android AppCompat工具栏中的文本居中?,android,xamarin,appcompatactivity,Android,Xamarin,Appcompatactivity,试图在Android工具栏中将TextView居中,但当有一个视图添加到后堆栈时,会丢失居中。似乎back项不是工具栏的一部分,这导致了问题 下面是工具栏的xml: <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/t

试图在Android工具栏中将TextView居中,但当有一个视图添加到后堆栈时,会丢失居中。似乎back项不是工具栏的一部分,这导致了问题

下面是工具栏的xml:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways">
<FrameLayout
android:background="@color/primary"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<!-- This is a centered title -->
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_gravity="center"
         android:layout_marginLeft="?attr/actionBarSize"
            android:layout_marginRight="?attr/actionBarSize"
        android:gravity="center_vertical|center_horizontal">
        <TextView
            android:id="@+id/toolbar_title"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Blah"
            android:textSize="18dp"
            android:textColor="@color/white"
            style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse" />
    </LinearLayout>
</FrameLayout>

当添加到后堆栈的活动显示“后退”按钮且文本居中丢失时:


问题在于对您的中心视图的误解

文本视图位于其父视图(LinearLayout)的中心,但不在工具栏的中心

将新项添加到工具栏(导航项)时,它会推动FrameLayout,但TextView会保持在其父项LinearLayout的中心,但不在 工具栏

TextView是LinearLayout的一项,位于其容器LinearLayout的中心

LinearLayout是FrameLayout的一项

FrameLayout是工具栏的一项


我希望它能帮助您。

您尝试过使用自定义工具栏视图吗?谢谢,了解了发生的情况。但是我如何在工具栏中居中,你能举个例子吗?我现在能想到的更好的方法是在工具栏中添加你自己的项目导航,这样你就可以更好地控制布局,并将文本视图居中到你的首选项。另一种不太优雅但有效的方法是,您可以检测导航项何时出现,并在文本视图的右侧添加一些额外的边距,以补偿导航项的位置,它看起来就像在中间一样。