Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align text in center of toolbar

In my application I am using a Toolbar. Now I want the title(label) to be displayed in the center of the Toolbar. When the home button (back button) is not shown then the title comes in the center, but when the back button is there the text moves little further from center. So how can I do this?

XML

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_list_detail"
        style="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/green">

        <TextView
            android:id="@+id/tv_ld_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Hello"
            android:gravity="center"
            android:textColor="#fff"
            android:textSize="@dimen/textSize"
            android:textStyle="bold" />

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

Code

toolbar = (Toolbar) findViewById(R.id.toolbar_list_detail);
setSupportActionBar(toolbar);
tvHeader = (TextView) toolbar.findViewById(R.id.tv_ld_header);
//rlToolbar = (RelativeLayout) toolbar.findViewById(R.id.rl_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.back);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
like image 739
androGuy Avatar asked Jun 23 '15 08:06

androGuy


1 Answers

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="?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);
like image 151
Rajan Bhavsar Avatar answered Nov 09 '22 12:11

Rajan Bhavsar