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

如何修改MaterialToolbar按钮的背景颜色及按下状态颜色?

解决MaterialToolbar按钮按下状态背景色不生效的问题

原因说明

直接给MaterialToolbar设置android:background只会修改Toolbar自身的背景,而菜单按钮、导航按钮是Toolbar内部的独立子控件,不会继承这个背景配置,所以你之前的selector不会作用到这些按钮上。

可行解决方案

方案1:通过主题样式全局修改Toolbar按钮状态色

这种方法会统一修改Toolbar内所有按钮的按下状态背景,步骤如下:

  1. 先完善你的状态选择器(补充默认状态,避免显示异常):
<!-- res/drawable/toolbar_item_selector.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/pressed_toolbox_item" android:state_pressed="true" />
    <!-- 默认状态设为透明,不影响按钮正常显示 -->
    <item android:drawable="@android:color/transparent" />
</selector>
  1. 在styles.xml中定义Toolbar专属样式:
<style name="CustomToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
    <!-- 给菜单按钮设置状态背景 -->
    <item name="actionItemBackground">@drawable/toolbar_item_selector</item>
    <!-- 如果需要修改导航按钮的背景,额外添加以下配置 -->
    <item name="navigationIcon">@drawable/ic_baseline_keyboard_arrow_up_24</item>
</style>
  1. 在布局中给MaterialToolbar应用该样式:
<com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    app:menu="@menu/webview_toolbar"
    style="@style/CustomToolbarStyle" />

方案2:给单个菜单按钮自定义布局

如果只想修改特定菜单按钮的状态色,可以给目标item指定自定义布局:

  1. 创建按钮布局文件(比如res/layout/toolbar_custom_menu_item.xml):
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:background="@drawable/toolbar_item_selector"
    android:src="@drawable/your_target_menu_icon" />
  1. 在菜单文件中引用这个自定义布局:
<!-- res/menu/webview_toolbar.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/target_menu_item"
        android:title="目标按钮"
        app:actionLayout="@layout/toolbar_custom_menu_item"
        app:showAsAction="always" />
</menu>

方案3:通过代码动态设置

如果需要更灵活的控制(比如根据业务逻辑动态切换),可以在代码中获取按钮控件并设置背景:

// Kotlin 示例
// 设置菜单按钮背景
main_toolbar.setOnMenuItemClickListener { menuItem ->
    val itemView = main_toolbar.findViewById<View>(menuItem.itemId)
    itemView.background = resources.getDrawable(R.drawable.toolbar_item_selector, theme)
    // 处理按钮点击逻辑
    true
}

// 设置导航按钮背景
val navView = main_toolbar.findViewById<View>(com.google.android.material.R.id.navigation_icon)
navView.background = resources.getDrawable(R.drawable.toolbar_item_selector, theme)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:48:18