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?
<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>
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);
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);
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