Android: How to Center title in ToolBar

The problem with simply adding a TextView in the Toolbar aligned center is adding menu items in the toolbar which will offset the centered text.

To get around this, I’ve layered the text on top of the Toolbar, not inside it. This way it doesn’t matter how many icons you add, it will not offset the centered text:

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
        </android.support.v7.widget.Toolbar>

        <TextView
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"/>

    </RelativeLayout>
</android.support.design.widget.AppBarLayout>

This way there is no need for any extra logic to compensate for the offset spacing of back buttons/overflow menu/search icons etc. on the toolbar, because the centered text is above it, not in it.

Leave a Comment