在 android 中按下时更改菜单按钮的颜色

change color of menu button when pressed in android

我制作了自定义菜单项,当按下按钮时,我想要的颜色背景变成了另一种颜色,如下图所示:

这是我的自定义样式:

 <style name="Menu">
        <item name="android:colorBackground">@color/white</item>
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:background">@drawable/item_bg_menu</item>
        </style>

item_bg_menu:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
    android:state_focused="true"
    android:state_pressed="true"
        android:drawable="@color/white" />

    <item
        android:state_pressed="true"
        android:drawable="@color/gray" />

</selector>

这是我使用菜单的方式:

app:popupTheme="@style/Menu"

最好最简单的方法是制作自己的风格

在本例中,样式名称是 Menu

<style name="Menu">
    <item name="android:colorBackground">@color/gray</item>   //color of background menu
    <item name="android:textColor">@color/white</item>       //text color
    <item name="android:listSelector">@drawable/item_bg_menu</item>     //this is for when button press color changed
    </style>

item_bg_menu

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:drawable="@color/black" />  //color when button press

</selector>

在您想要在收费栏中使用该菜单的地方只需添加此 app:popupTheme="@style/Menu"