73

大家好,

我对 Android 中的 ListView 有 2 个问题:

  1. 如何获得列表视图的焦点行的颜色?我尝试使用ListView.getSelector()方法,根据它的文档,它应该给我我正在寻找的东西,但它给了我一个 Drawable 对象,我不知道如何从中检索颜色(如果可能的话。 ..)。

  2. 如何设置列表视图的焦点行的颜色?在这里,我尝试在列表视图上使用setSelector()方法,将其传递给 ColorDrawable 对象,但这样做的结果是列表视图的整个背景都涂上了那种颜色......这不是我想要的当然...

谢谢!

4

2 回答 2

89

列表选择器drawable是一个StateListDrawable-它包含对列表可以是每个状态的多个drawable的引用,例如选择,聚焦,按下,禁用......

虽然您可以使用 检索可绘制对象getSelector(),但我不相信您可以Drawable从 a检索特定的StateListDrawable,而且似乎也不可能以编程方式直接从 a 检索颜色ColorDrawable

至于设置颜色,您需要StateListDrawable如上所述。您可以使用android:listSelector属性在列表中设置它,在 XML 中定义可绘制对象,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>
于 2010-01-10T18:45:58.597 回答
11

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

于 2013-04-08T07:36:08.783 回答