如何在Android中使用Selector Listview?

时间:2011-12-04 01:43:18

标签: android listview selector relativelayout

我有 lst_custom_view.xml

文件
 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|left"
        android:background="@drawable/list_choose"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginLeft="20dp"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit="marquee_forever"
            android:scrollHorizontally="true"
            android:singleLine="true"
            android:textColor="#ff000000"
            android:textSize="22dp" />
    </RelativeLayout>

Main.xml

中的Listview
<ListView
                    android:id="@+id/lstView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_weight="1"
                    android:background="@android:color/transparent"
                    android:cacheColorHint="@android:color/transparent"
                    android:divider="@drawable/menu_phancach"
                    android:dividerHeight="2dp"
                    android:visibility="visible">
         </ListView>

我使用Selector with Relativelayout的背景,名称为 list_choose.xml

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

当我按项目列表视图但未选择背景menu_content_hover时,它会显示RelativeLayout menu_content_hover的背景。我希望它在用户按下项目和选择时更改背景menu_content_hover,在用户滚动列表(未选中)时更改背景menu_content或选择其他项目。我使用simpleCursorAdapter。任何帮助?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

选择器应该是这样的:

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

    <item android:state_pressed="true" 
        android:drawable="@drawable/background_pressed" />
    <item android:state_focused="true"
        android:drawable="@drawable/background_focused" />
    <item android:state_selected="true" 
        android:drawable="@drawable/background_selected" />
    <item android:drawable="@drawable/background_default"/>

</selector>