如何为ListView设置选择器?

时间:2012-01-30 05:30:24

标签: java android

我遇到以下问题:我的应用程序具有白色背景和ListView的布局。如果我需要滚动这个ListView,那么它会改变黑色的颜色!我刚刚为ListView制作了选择器,但它并不适用。我的ListView:

        <ListView
            android:id="@+id/listViewLastUpdates"
            android:listSelector="@drawable/selector"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>

我的选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/green" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/green" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/white" /> <!-- default -->
</selector> 

我需要使用绿色作为高亮和白色作为背景(然后如果我滚动ListView它不会改变颜色)。请告诉我,我该如何解决?

2 个答案:

答案 0 :(得分:1)

在设置颜色时使用color selector代替drawable selector

制作color folder inside res并保存此颜色的xml选择器并使用它:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@color/green" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:color="@color/green" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:color="@color/green" /> <!-- pressed -->
    <item android:color="@color/white" /> <!-- default -->
</selector> 

答案 1 :(得分:1)

试试这个并告诉我它是否有帮助:

<ListView
    android:id="@+id/listViewLastUpdates"
    android:listSelector="@drawable/selector"
    android:background="@android:color/white"
    android:cacheColorHint="@android:color/transparent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>