You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将strings.xml中定义的字符串在Android应用顶部标题栏居中显示

Android顶部标题栏标题居中解决方案

你在AndroidManifest中配置的android:label对应系统默认标题栏/ActionBar的标题,默认左对齐,无法直接通过android:gravity或者strings.xml配置修改对齐方式,可通过以下两种方案实现居中:

方案1:全局主题修改(适合所有页面统一生效)

找到你应用使用的主题@style/Theme.Blue对应的定义文件(一般存放在res/values/themes.xml或styles.xml中),添加如下样式配置:

<!-- 原有Theme.Blue配置保持不变,新增以下item -->
<style name="Theme.Blue" parent="你的原有主题父类">
    <item name="actionBarStyle">@style/CenterTitleActionBar</item>
</style>

<style name="CenterTitleActionBar" parent="Widget.AppCompat.ActionBar">
    <item name="titleTextStyle">@style/ActionBarTitleCenter</item>
</style>

<style name="ActionBarTitleCenter" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:layout_gravity">center</item>
    <item name="android:gravity">center</item>
    <item name="android:textAlignment">center</item>
    <!-- 可直接在这里配置标题样式,替代strings.xml中的font标签,更符合开发规范 -->
    <item name="android:textSize">28sp</item>
    <item name="android:textColor">#444444</item>
    <item name="android:textStyle">bold</item>
</style>

修改完成后,你可以把strings.xml简化为:

<resources>
    <string name="app_name">Test</string>
</resources>

方案2:自定义Toolbar(灵活性更高,适合单个页面定制)

如果方案1适配有问题,或者需要对标题栏做更多自定义操作,推荐使用自定义Toolbar方案:

  • 步骤1:修改应用主题为无ActionBar类型,避免和自定义Toolbar冲突
<style name="Theme.Blue" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <!-- 原有其他配置保持不变 -->
</style>
  • 步骤2:创建自定义标题栏布局res/layout/custom_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:textColor="#444444"
        android:textStyle="bold"/>

</androidx.appcompat.widget.Toolbar>
  • 步骤3:在需要显示居中标题的Activity布局文件顶部引入自定义Toolbar
<!-- 放在根布局的第一个子控件位置 -->
<include layout="@layout/custom_toolbar" />
  • 步骤4:在Activity的onCreate生命周期中绑定自定义Toolbar
// Kotlin代码
val toolbar = findViewById<Toolbar>(R.id.custom_toolbar)
setSupportActionBar(toolbar)
// 隐藏系统默认标题,使用自定义Toolbar中的TextView
supportActionBar?.setDisplayShowTitleEnabled(false)
// Java代码
Toolbar toolbar = findViewById(R.id.custom_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
    getSupportActionBar().setDisplayShowTitleEnabled(false);
}

内容的提问来源于stack exchange,提问作者w1cked

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:06:03