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

Android Toolbar标题不显示及字号无法修改问题咨询

Toolbar标题不显示、字号无法修改的解决方案

一、Toolbar标题不显示的问题

排查和修复方式:

  1. 必须将Toolbar设置为ActionBar
    在Activity的onCreate方法中调用setSupportActionBar(toolbar),否则Toolbar仅作为普通View存在,默认不会显示标题:

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    
  2. 换用正确的命名空间属性
    AppCompat Toolbar的标题属性优先使用app命名空间,修改布局XML中的标题属性:

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="95dp"
        app:title="@string/ucc_it_online"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        style="@style/ToolBar"/>
    
  3. 检查是否存在遮挡情况
    虽然当前Toolbar高度95dp足够容纳50sp的文字,但可以暂时降低字号测试,同时确认没有其他View覆盖在Toolbar上方。

二、Toolbar标题字号无法修改的问题

直接在Toolbar的style中设置android:textSize不会生效,因为Toolbar的标题是内部的TextView,需要通过titleTextAppearance属性指定自定义文本样式:

第一步:在style.xml中添加标题文本样式

<style name="ToolbarTitleText" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textSize">50sp</item>
    <item name="android:textColor">@color/white</item>
</style>

第二步:修改Toolbar的style,引用上述文本样式

<style name="ToolBar" parent="Widget.AppCompat.Toolbar">
    <item name="android:background">@color/blue</item>
    <item name="titleTextAppearance">@style/ToolbarTitleText</item>
</style>

<style name="ToolbarWithTitle" parent="Widget.AppCompat.Toolbar">
    <item name="android:background">@color/blue</item>
    <item name="titleTextAppearance">@style/ToolbarTitleText</item>
</style>

如果不需要统一设置,也可以直接在布局XML中给单个Toolbar添加app:titleTextAppearance="@style/ToolbarTitleText"属性,单独控制其标题样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:40:25