Java how to set title in center in toolbar in android

Java how to set title in center in toolbar in android

To set the title in the center of the toolbar in an Android app, you can use the setTitle method of the Toolbar class and specify the Gravity value CENTER as an argument.

Here's an example of how you can do this in XML layout file:

refer ‮uttual:ot‬ri.com
<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textColor="@color/white"
        android:textSize="20sp"
        android:textStyle="bold" />

</androidx.appcompat.widget.Toolbar>

Alternatively, you can use the setTitle method in your Java code to set the title of the Toolbar:

Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Title");
toolbar.setTitleTextAppearance(this, R.style.ToolbarTitle);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
toolbar.setGravity(Gravity.CENTER);

In this example, the setTitleTextAppearance method is used to set the appearance of the title text, and the setTitleTextColor method is used to set the color of the title text. The setGravity method is used to set the gravity of the title to CENTER.

Created Time:2017-11-03 23:27:12  Author:lautturi