I want to show title of a toolbar
in center so i am using custom textview
to show title like this :
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Title"
android:textColor="@android:color/white"
android:textSize="25sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
Java Code :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView title = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
title.setText("Title");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
Result :
Title text not showing in center properly if I am enabling back button of toolbar.
and things are working fine if back button of toolbar is not enabled i.e.
if
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
Result :
Now , I want to show title in center with Back button enabled of toolbar also. How to do this ? Any help
1) You need to remove this
title.setText("Title");
because already in xml file.
2) Use
getSupportActionBar().setDisplayShowTitleEnabled(false);
3) Set layout gravity for TextView
android:layout_gravity="center"
Edit:
Also change height and width of TextView
to wrap_content
.