Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to Center title in ToolBar

Tags:

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.

like image 529
Umesh Kumar Saraswat Avatar asked Apr 04 '15 06:04

Umesh Kumar Saraswat


People also ask

How do I center text in toolbar?

suggest use android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" instead. To keep using default styles for the customised TextView, try something like style="@style/TextAppearance.

How do I change the title text bar in android?

First, add a font file in the src/main/assets/fonts/ of your project. Then create variables for Toolbar and text title and call the method findViewById(). Create a new Typeface from the specified font data. And at last setTypeface in text title.


1 Answers

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.

like image 77
jesobremonte Avatar answered Sep 18 '22 18:09

jesobremonte