1

I know the layout way to set toolbar title in center. (Have a TextView in Toolbar)

I am looking for java way for same. This is my toolbar layout

<android.support.v7.widget.Toolbar
  android:id="@+id/toolbar"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@color/colorPrimary"
  android:minHeight="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>

This is how i am setting toolbar title in activity:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("MY ORDERS");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Title is left aligned by default.

Is there any way (without changing layout) to make title centered aligned?

Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131

1 Answers1

0

Toolbar widget can have child views, which can be used to customize the look and feel of Toolbar. The way to center text will be to use TextView as child of Toolbar, and then customizing it.

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/app_name"
        android:textColor="@color/black" />

</android.support.v7.widget.Toolbar>
capt.swag
  • 10,335
  • 2
  • 41
  • 41