Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Center the title of the Toolbar [duplicate]

i have a Toolbar in my app like that:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="#263355"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

And i add the title as that:

getSupportActionBar().setTitle(title);

I've read that Android toolbar center title and custom font

But if i change the xml of the toolbar, i don't know how to change the value of the TextView. Someone can help me ?

like image 703
benjyspider Avatar asked May 13 '15 09:05

benjyspider


People also ask

How do I center my toolbar title?

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. Widget.

How can I center my action bar title in android Studio?

How do you make it appear in the center? ActionBar actionBar = getActionBar(); actionBar. setDisplayShowTitleEnabled(true); actionBar. setTitle("Canteen Home"); actionBar.


1 Answers

Do not use getSupportActionBar().setTitle(title); to set the title, if you have a custom Toolbar layout.

Instead, assuming your XML layout looks like this:

        <!-- Toolbar -->
        <android.support.v7.widget.Toolbar
            android:id="@+id/main_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/main_toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/main_toolbar_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </android.support.v7.widget.Toolbar>

You need to call, somewhere in your MainActivity's onCreate() probably:

((TextView) findViewById(R.id.main_toolbar_title)).setText("Title!");
like image 99
Karim Avatar answered Nov 09 '22 23:11

Karim