I'm trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).
At the moment, i'm using the good old ActionBar, and I was setting the title to empty value, and using setCustomView
to put my custom font TextView and center it using ActionBar.LayoutParams.
Is there a better way to do that? Using the new Toolbar as my ActionBar.
To use a custom title in your Toolbar
all you need to do is remember is that Toolbar
is just a fancy ViewGroup so you can add a custom title like so:
<android.support.v7.widget.Toolbar android:id="@+id/toolbar_top" android:layout_height="wrap_content" android:layout_width="match_parent" android:minHeight="?android:attr/actionBarSize" android:background="@color/action_bar_bkgnd" app:theme="@style/ToolBarTheme" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Toolbar Title" android:layout_gravity="center" android:id="@+id/toolbar_title" /> </android.support.v7.widget.Toolbar>
This means that you can style the TextView
however you would like because it's just a regular TextView
. So in your activity you can access the title like so:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top); TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
This's just to help to join all pieces using @MrEngineer13 answer with @Jonik and @Rick Sanchez comments with the right order to help to achieve title centered easly!!
The layout with TextAppearance.AppCompat.Widget.ActionBar.Title
:
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay"> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title" android:layout_gravity="center" /> </android.support.v7.widget.Toolbar>
The way to achieve with the right order:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); setSupportActionBar(toolbar); mTitle.setText(toolbar.getTitle()); getSupportActionBar().setDisplayShowTitleEnabled(false);
Please don't forget to upvote @MrEngineer13 answer !!!
Here is a sample project ToolbarCenterTitleSample
Hope to help somebody else ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With