Search code examples
androidandroid-toolbar

Toolbar title not in center when Back Button is enable


I'm trying to display my toolbar title in the center and to do it I use the method which is given in this answer :-Toolbar Center title

However, when I enable back button in my activity by following code:

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setDisplayShowHomeEnabled(true);

The title of toolbar doesn't show up in the center but slightly off-centered towards the right.

How can I achieve centered title without being affected by the back button or menu bar?


Solution

  • Add a TextView inside the Toolbar & don't forget to set the following attribute inside your TextView.

    android:layout_marginRight="?android:attr/actionBarSize"

    OR

    android:layout_marginEnd="?android:attr/actionBarSize"

    code snippet:

    <android.support.v7.widget.Toolbar
        android:id="@+id/custom_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:background="@android:color/holo_red_dark">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="abc"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:layout_marginRight="?android:attr/actionBarSize"
            android:gravity="center"/>
    
    </android.support.v7.widget.Toolbar>
    

    Refer to this tutorial for more information.