Android: How to Center title in ToolBar

Umesh Kumar Saraswat picture Umesh Kumar Saraswat · Apr 4, 2015 · Viewed 91.1k times · Source

I am using ToolBar in my project first time, so i do not know how to customized the toolbar in android. I need to centered title in to the tool bar and how to do that please tell me.

Thank in advance.

Answer

jesobremonte picture jesobremonte · Sep 1, 2016

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.