android listview selector

The solution by dglmtn doesn't work when you have a 9-patch drawable with padding as background. Strange things happen, I don't even want to talk about it, if you have such a problem, you know them.

Now, If you want to have a listview with different states and 9-patch drawables (it would work with any drawables and colors, I think) you have to do 2 things:

  1. Set the selector for the items in the list.
  2. Get rid of the default selector for the list.

What you should do is first set the row_selector.xml: 


复制代码
<? xml version="1.0" encoding="utf-8" ?>
< selector  xmlns:android ="http://schemas.android.com/apk/res/android"   >
     < item  android:state_enabled ="true"  
     android:state_pressed
="true"  android:drawable ="@drawable/list_item_bg_pressed"   />
     < item  android:state_enabled ="true"
     android:state_focused
="true"  android:drawable ="@drawable/list_item_bg_focused"   />
     < item  android:state_enabled ="true"
     android:state_selected
="true"  android:drawable ="@drawable/list_item_bg_focused"   />
     < item
     
android:drawable ="@drawable/list_item_bg_normal"   />
</ selector >

 

Don't forget the android:state_selected. It works like android:state_focused for the list, but it's applied for the list item.

Now apply the selector to the items (row.xml): 

复制代码
<? xml version="1.0" encoding="utf-8" ?>
< RelativeLayout  xmlns:android ="http://schemas.android.com/apk/res/android"
android:layout_width
="fill_parent"
android:layout_height
="wrap_content"
android:orientation
="horizontal"
android:background
="@drawable/row_selector"
>
...
</ RelativeLayout >
复制代码

 

Make a selector for the list (to get rid of the default one which ruins the effect) - list_selector.xml:

 

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

Notice that it makes all the states transparent. That's what I meant by getting rid of the default states.

Last, but not least - apply the selector to the listview:

 

< ListView
    
android:id ="@+id/android:list"
    ...
    android:listSelector
="@drawable/list_selector"
    
/>
复制代码

 

复制代码

转自http://www.cnblogs.com/tt_mc/archive/2012/05/30/2526599.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值