Android:按下菜单项时的背景色

时间:2014-10-27 10:03:43

标签: android background-color menuitem

我尝试在按下时将背景颜色更改为菜单项。按下时更改背景颜色,但不更改颜色。

WHISED:

  • 背景:深灰色
  • 背景按下:橙色

获得:

  • 背景:深灰色
  • 背景按下:蓝色(默认Android)

我能做什么?感谢

enter image description here

Styles.xml

<style name="AppTheme2" parent="android:Theme.Holo">  
    <item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
</style>

<style name="MyApp.PopupMenu" parent="android:Widget.Holo.ListPopupWindow">
    <item name="android:popupBackground">@drawable/menu_item_selector</item>
</style>

menu_item_selector.xml

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

<item android:drawable="@drawable/menu_item_fondo_pressed" android:state_focused="true"/>
<item android:drawable="@drawable/menu_item_fondo_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/menu_item_fondo"/>

</selector>

1 个答案:

答案 0 :(得分:2)

回答很少,但找到了问题的解决方案。

styles.xml 中,您拥有 AppTheme

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:dropDownListViewStyle">@style/ListViewStyle</item>
    <item name="dropDownListViewStyle">@style/ListViewStyle</item>
    <item name="popupMenuStyle">@style/PopupMenu</item>
    <item name="textAppearanceLargePopupMenu">@style/PopupMenuTextAppearanceLarge</item>
    <item name="textAppearanceSmallPopupMenu">@style/PopupMenuTextAppearanceSmall</item>
    <item name="android:textAppearanceLargePopupMenu">@style/PopupMenuTextAppearanceLarge</item>
    <item name="android:textAppearanceSmallPopupMenu">@style/PopupMenuTextAppearanceSmall</item>
</style>

popupMenuStyle 适用于popupMenu本身,在这种情况下,我们可以在 popupBackground 项目中更改未选定的背景,就像这样(但你已经知道):

<style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">@drawable/selector_popup_menu_bg</item>
    <item name="android:textColor">@color/text_color_white</item>
    <item name="android:dropDownSelector">@drawable/selector_popup_menu_dropdown</item>
</style>

还有 textColor dropDownSelector 项目,它们在我测试过的设备上没有做任何事情,但我也在这里更改这些以防万一,因为parent( Widget.PopupMenu )也使用它们。

正确更改这些项目的方法是更改​​ AppTheme 中的内容,就像我在 AppTheme 代码中显示的一样。我不会显示textAppearances的代码,因为它不是主题。

我将这些项目中的每一项添加两次(使用和不使用&#34; android:&#34;前缀)的原因是使其在5.0和棒棒糖前设备上都能正常工作。唯一的例外是 popupMenuStyle ,只需要没有&#34; android:“前缀的项目,如果您使用的是Popup的框架版本,但是如果您使用{{1} }版本,那么您需要support.v7see this StackOverflow answer for more info)。

因此,要选择不同的项目背景,我们只需在 dropDownListViewStyle 中更改它(我已添加 divider ):

android:popupMenuStyle

有趣的部分是 listSelector ,它是所选项目的背景。如果我们只在那里添加@color,那么所选的项目将无法正确无效(即使你将选择移出它也将保持选中状态),为了使其正确而不是颜色,需要使用选择器:

<强> selector_popup_menu_dropdown.xml

<style name="ListViewStyle" parent="@android:style/Widget.ListView">
    <item name="android:listSelector">@drawable/selector_popup_menu_dropdown</item>
    <item name="android:divider">@color/text_color_white</item>
    <item name="android:dividerHeight">1dp</item>
</style>

<?xml version="1.0" encoding="utf-8"?>

对于这种琐碎的事情有点太长的解释,但我们直到最后。 Yaay!