26

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?

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33

8 Answers8

70

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.

Arshak
  • 3,197
  • 1
  • 25
  • 33
  • 3
    android:layout_marginEnd="?android:attr/actionBarSize" also works great – Ender2050 Jan 20 '19 at 22:23
  • 3
    You need to use `android:layout_gravity="center"` & `android:layout_width="wrap_content"` for `TextView`. There is no. need for `android:layout_marginRight` or something else. – ardiien Feb 09 '19 at 14:08
  • 1
    @YaroslavOvdiienko If you do that then you’l notice that the text is slightly positioned towards the right instead of exactly center when back button is visible(as it is being centered from the available space). So, this is just a workaround. – Arshak Feb 09 '19 at 14:21
  • Maybe I`m blind but it is not true. – ardiien Feb 09 '19 at 14:29
  • @YaroslavOvdiienko hahaha..i just tried on Android studio it was still leaving space towards left..why don’t you post an answer maybe it might help someone. – Arshak Feb 09 '19 at 14:32
  • @JohnnyFive The title starts at 72dp when the back button is visible & by default there's a toolbar margin end of 16dp. So, ?actionBarSize (56dp) + default toolbar end margin(16dp) = 72dp. You could directly mention 56dp instead of actionBarSize. Refer this [link](https://material.io/design/components/app-bars-top.html#specs) for design guidelines. – Arshak Jun 04 '19 at 16:51
  • How to implement it without a toolbar. – Shyamaly Lakhadive Jan 26 '22 at 12:27
  • @ShyamalyLakhadive You can make use of Linear Layout or Relative Layout instead of toolbar to make it look like a toolbar and customize it based on your needs. – Arshak Jan 26 '22 at 15:20
  • @Arshak I am using the action bar and textview is programmatically included where I am using Linearlayout still it is not centered. In my action bar "home button, title, menu" are present. How to work on it? – Shyamaly Lakhadive Jan 27 '22 at 05:26
  • @ShyamalyLakhadive AFAIK Action bar got deprecated with API 21. Please make use of Toolbar which could resolve your issue. – Arshak Jan 27 '22 at 19:33
6

Having a placeholder image the same size as the back arrow and setting it to be invisible when the back arrow is not shown and gone when it's displayed did the trick for me.

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:background="@color/blue"
    android:minHeight="?attr/actionBarSize"
    app:contentInsetEnd="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetStart="0dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<ImageView
    android:id="@+id/iv_placeholder"
    android:layout_width="72dp"
    android:layout_height="48dp"
    android:src="@drawable/ic_actionbar_hamburger"
    android:visibility="invisible"/>


<TextView
    android:id="@+id/logo_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="?attr/actionBarSize"
    android:gravity="center"
    android:text=""
    android:textColor="@color/white"
    android:textStyle="normal"/>

</android.support.v7.widget.Toolbar>

enter image description here

enter image description here

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81
2

Just add android:paddingEnd="72dp; to the Toolbar layout.

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    app:contentScrim="@color/colorPrimary"
    app:layout_collapseMode="pin"
    android:paddingEnd="72dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
    app:title="Title"/>
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Fazal
  • 122
  • 2
  • 9
  • make marginEnd or paddingEnd 72dp instead 64dp to be exact. i recent findout on closer inspection – Fazal Aug 28 '18 at 06:15
2

Just put your content in a child view inside the Toolbar tag in XML, using the following attributes:

android:layout_width="wrap_content"
android:layout_gravity="center"

Offical docs for Toolbar state:

One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view's LayoutParams indicates a Gravity value of Gravity#CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.

This works for me, using androidx.appcompat.widget.Toolbar with a child view.

ade.se
  • 1,644
  • 1
  • 11
  • 11
1

The reason why the title is not centered when you use a back button as navigation icon, is that navigation icon is represented as AppCompatImageButton and is added to the same layout as your title TextView. Using Arshak's answer is not a bad idea, but ?android:attr/actionBarSize is not a good way to define the end margin. As the action bar height is probably the same size as icon's width, it might work, but might not work on all devices. Could be a good idea to specify this size from material design guidelines.

arenaq
  • 2,304
  • 2
  • 24
  • 31
0

In my case I was using an imageview inside the toolbar which I didnt want shifting around while navigating between fragments of a activity. I kept it centered by placing it out the toolbar. I used constraintlayouts

<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">



</com.google.android.material.appbar.MaterialToolbar>

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="@id/toolbar"
    app:layout_constraintBottom_toBottomOf="@id/toolbar"
    android:src="@drawable/ic_logo"
    tools:ignore="ContentDescription" />
 ...

</androidx.constraintlayout.widget.ConstraintLayout>
Njuacha Hubert
  • 388
  • 3
  • 14
0

I think the nicest and most up-to-date method is to have full control over the appbar. This way you can change other things from textview location.

<androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="@string/app_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:textSize="20dp"
                android:textColor="?attr/colorPrimary"
                android:layout_centerInParent="true"
                android:layout_marginEnd="20dp"/>

        </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>

You can use this directly inside your activity. However, you may need to change the active toolbar by making such a definition in the activity where you added this toolbar.

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
-1

Dont set propterties like this

mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setDisplayShowHomeEnabled(true);

Do like this

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        // Title and subtitle
        toolbar.setTitle(R.string.about_toolbar_title);
        toolbar.setSubtitleTextColor(Color.WHITE);
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setBackgroundColor(getResources().getColor(
                R.color.themeToolbarColor));
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        toolbar.setNavigationOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
               finish();  // to go back  finish() will do your work.
                //mActionBar.setDisplayHomeAsUpEnabled(true);
                //mActionBar.setDisplayShowHomeEnabled(true);
            }
        });
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41