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

标签 java android title toolbar

<分区>

我的应用程序中有一个这样的工具栏:

<?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" />

然后我将标题添加为:

getSupportActionBar().setTitle(title);

我读过 Android toolbar center title and custom font

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

最佳答案

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

相反,假设您的 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>

您需要调用,在您的MainActivityonCreate() 中的某处可能:

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

关于java - Android - 将工具栏的标题居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30210931/

相关文章:

android - 如何在 ImageButton (Android) 中访问/获取图像的资源 ID

javascript - document.title 问题 ie8

java - 加载程序约束违规

java - 设置按下 Tab 时 JComboBox 中的插入符位置

Android 在 Activity 中持久化一个 SnackBar

android - 返回 EntityUtils.toString(response) 的究竟是什么?

某个类的所有跨度的标题的css

python - 向单个绘图添加标题或标签

java - 我需要有关“Deal or no Deal”Java 游戏的帮助

java - 无法在我的 jhipster 应用程序上加载其他配置文件