I'm trying to display my toolbar title in the center and to do it I use the method which is given in this answer :-Toolbar Center title
However, when I enable back button in my activity
by following code:
toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setDisplayShowHomeEnabled(true);
The title of toolbar doesn't show up in the center but slightly off-centered towards the right.
How can I achieve centered title without being affected by the back button or menu bar?
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. AppCompat.
Show back button using actionBar. setDisplayHomeAsUpEnabled(true) this will enable the back button. Custom the back event at onOptionsItemSelected. This will enable the back function to the button on the press.
Add a TextView inside the Toolbar & don't forget to set the following attribute inside your TextView.
android:layout_marginRight="?android:attr/actionBarSize"
OR
android:layout_marginEnd="?android:attr/actionBarSize"
code snippet:
<android.support.v7.widget.Toolbar android:id="@+id/custom_toolbar" android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:background="@android:color/holo_red_dark"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="abc" android:textColor="@android:color/white" android:textSize="20sp" android:layout_marginRight="?android:attr/actionBarSize" android:gravity="center"/> </android.support.v7.widget.Toolbar>
Refer to this tutorial for more information.
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