You need to enable JavaScript to run this app. Android开发:如何移除Toolbar阴影并将Home标题设为居中
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何移除Toolbar阴影并将Home标题设为居中

安卓Toolbar阴影移除&标题居中解决方案

移除Toolbar阴影

阴影并非来自Toolbar本身,而是外层AppBarLayout默认自带的Z轴高度阴影,仅给Toolbar设置app:elevation="0dp"无法生效,需要给AppBarLayout也设置高度为0:
在AppBarLayout标签中新增app:elevation="0dp"属性即可,修改后的核心布局代码如下:

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/Theme.AIT.AppBarOverlay"
    app:elevation="0dp"> <!-- 新增该属性移除阴影 -->

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#2398f4"
        app:popupTheme="@style/Theme.AIT.PopupOverlay"
        app:elevation="0dp"/>

</com.google.android.material.appbar.AppBarLayout>

Toolbar标题居中显示

默认Toolbar的标题会靠左对齐,且位置会受导航按钮、菜单图标影响,不推荐用调整边距的方式实现居中,最稳定的方案是自定义标题控件,不使用系统默认的标题逻辑:
直接在Toolbar标签内部添加居中的TextView作为标题,修改后的Toolbar代码如下:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="#2398f4"
    app:popupTheme="@style/Theme.AIT.PopupOverlay"
    app:elevation="0dp">

    <!-- 自定义居中标题 -->
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Home"
        android:textColor="#FFFFFF"
        android:textSize="18sp"/>

</androidx.appcompat.widget.Toolbar>

使用说明:

  • 无需再调用系统默认的setTitle()方法,直接通过上述TextView的id在代码中动态修改标题内容即可
  • 可根据需求调整标题的颜色、字号、样式,适配不同设计要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 06:57:04