在Android下拉列表导航中设置所选项目背景颜色

时间:2013-12-30 20:07:15

标签: android android-actionbar android-spinner

我认为这是一个简单的问题,但我无法找到我的具体问题的答案。

我已阅读this great article,并希望在动态条形码的Android下拉列表中设置所选项目的背景颜色(我没有使用Sherlock和我' m目标ICS +),如下图所示:

Dropdown list screenshot

到目前为止,我已经以这种方式设置了我的主题:

<resources>
  <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>        
  </style>
  <style name="MyDropDownListView" parent="android:style/Widget.Holo.ListView.DropDown">
    <item name="android:listSelector">@drawable/ad_selectable_background</item>
  </style>
</resources>

这是我的 ad_selectable_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"
              android:exitFadeDuration="@android:integer/config_mediumAnimTime" >
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:drawable="@android:color/transparent" />
</selector>

我的下拉视图资源是:

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

按下状态有效,但是当您打开菜单时,不会显示任何选项。 我想使用选择器将其设置为 holo_blue_light ,但我无法使用XML 找到正确的语法

如果可能的话(我没有使用任何代码),我正在寻找一个只有XML的答案。谢谢!

1 个答案:

答案 0 :(得分:6)

显然,这很简单!

我必须编辑 ad_selectable_background.xml 以使用已检查状态(正如我之前所做的那样,但我错过了下面的主题):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
              android:exitFadeDuration="@android:integer/config_mediumAnimTime" >
    <item android:state_pressed="false" android:state_checked="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:drawable="@android:color/transparent" />
</selector>

然后通过添加 android:spinnerDropDownItemStyle 项并禁用 checkMark 来编辑主题(因为我不想要单选按钮) ),就这样:

<resources>
  <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
    <item name="android:spinnerDropDownItemStyle">@style/MySpinnerDropDownItem</item>
  </style>
  <style name="MyDropDownListView" parent="android:style/Widget.Holo.ListView.DropDown">
    <item name="android:listSelector">@drawable/ad_selectable_background</item>
  </style>
  <style name="MySpinnerDropDownItem" parent="android:style/Widget.DropDownItem.Spinner">
    <item name="android:background">@drawable/ad_selectable_background</item>
    <item name="android:checkMark">@null</item>
  </style>
</resources>