How to center the title of an activity in the toolbar in such a way that it works also with the toolbar back button displayed ?
Currently, the best solution I have found is to had a 60dp margin if the back button is displayed.
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.
Toolbar was introduced in Android Lollipop, API 21 release and is the spiritual successor of the ActionBar. It's a ViewGroup that can be placed anywhere in your XML layouts. Toolbar's appearance and behavior can be more easily customized than the ActionBar.
When using ONLY the back button, this worked for me. In xml:
<android.support.v7.widget.Toolbar
android:id="@+id/tb_title_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textAllCaps="true"
android:textColor="#2B2B2B"
android:textSize="14sp" />
</android.support.v7.widget.Toolbar>
In java code:
int contentInsetStartWithNavigation = mTitleContainer.getContentInsetStartWithNavigation();
mTitleContainer.setContentInsetsRelative(0, contentInsetStartWithNavigation);
I don't know how is the best practice, but you can try this workaround using custom back button inside the toolbar. The layout code:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/toolbar_back_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:src="@drawable/ic_back" />
<TextView
android:id="@+id/toolbar_title"
style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
and the code in activity:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
ImageView backButton = (ImageView) findViewById(R.id.toolbar_back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
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