Trying to center a TextView in Android Toolbar, but when there's a view added to the back stack lost the centering. Seems the back item is not part of the toolbar and this causes the problem.
Here the xml for the toolbar:
<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>
When no back stack is centered:
When Activity added to back stack shows the back button and text centering is lost:
The problem is a misperception of the center TexView that you are having.
The TextView is on the center of its father(LinearLayout) but is NOT in the center of the Toolbar.
When you add a new item to the Toolbar (the navigation item), it's pushing the FrameLayout, but the TextView keep on the center of its father the LinearLayout, BUT IS NOT IN THE CENTER OF THE TOOLBAR.
The TextView is an item of LinearLayout, and is on the center of its container the LinearLayout.
LinearLayout is an item of the FrameLayout.
FrameLayout is an item of the Toolbar.
I hope it helps you.