How to change font,size of text and set text position center ToolBar Android?

I need to change the font size, the font itself, and center the text in the ToolBar. I took a template from Bottom Navigation Activity studio.

I was trying setting the text size in themes.xml (I was able to change the background color and text color there)

<style name="CustomToolBarStyle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="titleTextColor">@color/black</item>
<item name="android:background">@color/white</item>

I was trying to use this option in themes.xml:

<item name="android:gravity">center</item>

It didnt help. I tried to follow this instruction: https: //stackoverflow.com/questions/26533510/android-toolbar-center-title-and-custom-font Throws android.support.v7.widget.Toolbar into an error and get a crash.

ToolBar

NavbarTemplate

Answer

If you’re using androidx don’t use android.support.v7.widget.Toolbar.

You have to use androidx.appcompat.widget.Toolbar.

Create toolbar.xml in res/layout. Put this code:

<?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".MainActivity">
    
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
    
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="yourToolBarBackgroundColor"
                >
    
                <TextView
                    android:id="@+id/toolbar_title"
                    style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:layout_gravity="center"
                    android:text="TestToolBar"
                    android:fontFamily="yourFont"
                    android:textSize="yourSizeOfText"
                    android:textColor="yourTextColor" />
    
            </androidx.appcompat.widget.Toolbar>
    
        </com.google.android.material.appbar.AppBarLayout>
    
        <include layout="@layout/activity_main" />
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

Disable ActionBar in themes.xml:

<style name="Theme.YourProject" parent="Theme.MaterialComponents.DayNight.NoActionBar">

For night theme you have to do same thing in themes.xml(night)

Then in MainActivity.java in onCreate:

setContentView(R.layout.toolbar);