Align text in the center of the toolbar

In my application I use Toolbar . Now I want the name (label) to appear in the center of the toolbar. When the home button (back button) is not displayed, the name appears in the center, but when the back button is there, the text moves a little further from the 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); 
+5
source share
2 answers

To use a custom title on a toolbar, all you have to do is remember that the toolbar is just a fancy ViewGroup, so you can add your own title like this:

 <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 TextView, but you want to, because it's just a regular TextView. Therefore, in your activity, you can access the name like this:

 Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top); TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title); 
+2
source

To center the title on the toolbar, you must add android: layout_gravity = "center" remove android: gravity = "center" change android: layout_width = "match_parent" in android: layout_width = "wrap_content" in your TextView.

 <TextView android:id="@+id/tv_ld_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello" android:layout_gravity="center" android:textColor="#fff" android:textSize="@dimen/textSize" android:textStyle="bold" />` 
-2
source

All Articles