Saturday, 28 May 2016

Toolbar title in center

If you want your title text to be in center of your toolbar, you have two simple ways to do it.
First approach:-
Remember that the Toolbar is just a ViewGroup like others. So you can simply add Views into it.
In this case, you need a TextView inside a Toolbar at center position. So, simply define a layout for your toolbar containing a textview like this:

app_bar.xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Some Fancy Title"
        android:gravity = "center"
        android:id="@+id/toolbar_title" />

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

Then just include this layout in activity's XML file like:

<include
        layout="@layout/app_bar"/>

Then, in your Java file(Activity.java) access your toolbar and textview as follows:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

Since the textview gravity is already set to "center", it will display the text in center of the toolbar.


Second approach:-
You can just use the below method and pass your toolbar variable as parameter to it to make your title centered.

public static void centerToolbarTitle(final Toolbar toolbar) {
        final CharSequence title = toolbar.getTitle();
        final ArrayList<View> outViews = new ArrayList<>(1);
        toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
        if (!outViews.isEmpty()) {
            final TextView titleView = (TextView) outViews.get(0);
            titleView.setGravity(Gravity.CENTER_HORIZONTAL);
            final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.setMargins(0,0,60,0);
            toolbar.requestLayout();
        }
    }

Thas'it..!!! Enjoy!!


2 comments:

  1. can i do it without writing java code i mean by writing string.xml and style.xml ???

    ReplyDelete
  2. 2nd approach worked for me for inbuilt toolbar. but title is in not in centre when one menu item shows in title bar. it shifts little towards left. any idea how to make it in centre?

    ReplyDelete