Java Android - 将工具栏的标题居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30210931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:19:50  来源:igfitidea点击:

Android - Center the title of the Toolbar

javaandroidtitletoolbar

提问by benjyspider

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

我读过Android 工具栏中心标题和自定义字体

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 ?

但是如果我更改工具栏的xml,我不知道如何更改TextView 的值。有人可以帮助我吗?

采纳答案by Karim

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

getSupportActionBar().setTitle(title);如果您有自定义工具栏布局,请不要用于设置标题。

Instead, assuming your XML layout looks like this:

相反,假设您的 XML 布局如下所示:

        <!-- 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:

您需要在您的MainActivity's 中的某个地方打电话onCreate()

((TextView) findViewById(R.id.main_toolbar_title)).setText("Title!");