【问题标题】:How to change the color of selected item of ListView (which is not a custom ListView)如何更改 ListView 选定项的颜色(不是自定义 ListView)
【发布时间】:2012-04-15 07:10:12
【问题描述】:

我知道如何更改 CUSTOM ListView 选定项的颜色。但我不知道如何更改普通 ListView 的颜色。

我试过这个:

<ListView android:id="@id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    android:listSelector="@drawable/listitemselector">
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:state_pressed="true"
    android:drawable="@color/light_blue"></item>
</selector>

但这只是改变了整个 ListView 的颜色。我不想仅仅为了选择器颜色更改而实现 CUSTOM ListView。请为此提供解决方案。

【问题讨论】:

  • 请发布您的适配器源

标签: android listview


【解决方案1】:

尝试使用形状作为背景,而不是简单的颜色。这是我的一个项目中的一个示例:

listselector_blue.xml:

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

selector_state_blue.xml:

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

    <gradient
        android:angle="270"
        android:endColor="#FF91B2FF"
        android:startColor="#4491B2FF" />

    <corners android:radius="10px" />

</shape>

带有ListView的Activity的布局xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView android:id="@+id/list1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:listSelector="@drawable/listselector_blue" />

</LinearLayout>

【讨论】:

  • 非常感谢您的解决方案。但我不知道它为什么起作用。为什么它适用于“形状”而不适用于“颜色”???
  • 干得好,但我只能在选择列表视图时看到选定的颜色。一旦我用手指提起listView,它就会显示正常的颜色。我想重新邮寄选定的索引。那么该怎么办呢?
  • 需要存储被点击列表行的index或者id。然后您需要编写您的适配器,以便它使用不同的背景绘制选定的行。至少这是我通常实现这一点的方式。
  • @ZsomborErdődy-Nagy:谢谢。但是在实现这个之后,如果我滚动列表,那么选定的索引是否会被颜色改变?
  • 我不确定你的意思。用户单击一行,它被选中。之后,当用户在 ListView 中滚动时,所选行应保持不变。滚动手势不会触发行上的点击监听器。
【解决方案2】:

不要在 LISTVIEW 标记中使用此选择器。而是在列表视图中使用此选择器,即如果您使用 xml 来扩展列表视图(行视图),只需在该 xml 中使用此选择器。

【讨论】:

  • 我知道如何将其设置为“行视图”。但我应该为此实现 CUSTOM listView。我想在 NORMAL listview 中实现而不膨胀 listview 行的视图。
猜你喜欢
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 2012-10-10
  • 2014-10-25
相关资源
最近更新 更多