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

Android开发求助:ActionBar标题无法居中问题

解决Toolbar标题居中显示的问题

嘿,我看了你折腾Toolbar标题居中的代码,踩过同款坑的我来给你支几招!你之前尝试的setGravity和XML gravity属性没生效,核心原因是Toolbar默认会给导航图标、菜单等元素预留空间,同时自带左右内边距,导致你的TextView虽然设置了match_parent,但实际可用宽度被压缩了,没法在整个Toolbar范围内居中。

下面是两种亲测有效的解决方案:

方案一:调整TextView布局参数+清除Toolbar内边距

直接修改你的Toolbar布局文件,做这几个改动:

  1. 给Toolbar添加app:contentInsetStart="0dp"和app:contentInsetEnd="0dp",清除默认的左右内边距
  2. 将TextView的layout_width改为wrap_content,避免被Toolbar的内容区域限制
  3. 给TextView添加app:layout_gravity="center",让它在Toolbar的整个宽度上居中

修改后的Toolbar XML代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    app:titleTextAppearance="@style/Toolbar.TitleText"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:contentInsetStart="0dp"
    app:contentInsetEnd="0dp">

    <TextView
        android:id="@+id/text_view_toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textColor="@color/text_color"
        android:textSize="@dimen/tool_bar_text_size"
        android:gravity="center"
        app:layout_gravity="center"/>
</android.support.v7.widget.Toolbar>

这样即使你启用了HomeAsUp返回箭头,标题也能稳稳地在Toolbar水平中心位置显示。

方案二:嵌套RelativeLayout强制居中

如果方案一没解决问题,可以试试在Toolbar里嵌套一个RelativeLayout,让TextView在这个占满Toolbar的容器里居中,彻底绕过Toolbar的内容区域限制:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    app:titleTextAppearance="@style/Toolbar.TitleText"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_view_toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textColor="@color/text_color"
            android:textSize="@dimen/tool_bar_text_size"
            android:gravity="center"
            android:layout_centerInParent="true"/>
    </RelativeLayout>
</android.support.v7.widget.Toolbar>

这个方法兼容性更好,不管Toolbar有没有导航图标或菜单,都能保证标题居中。

最后提一句:你Java代码里那些注释掉的setGravity可以不用啦,XML里的设置已经足够生效了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:19:47