Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toolbar title not in center when Back Button is enable

Tags:

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?

like image 567
Shaishav Jogani Avatar asked Jul 26 '16 06:07

Shaishav Jogani


People also ask

How do I center the title bar in Android Studio?

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.

How do I add the toolbar back on my Android?

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.


1 Answers

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.

like image 158
Arshak Avatar answered Sep 22 '22 12:09

Arshak