ListView项目阴影+自定义选择器

时间:2013-06-26 15:04:22

标签: android listview layout selector shadow

我想在ListView项目中删除阴影并应用自定义选择器。但我不知道如何同时应用它们。

这是shadow.xml

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <shape android:shape="rectangle">
              <solid android:color="@android:color/darker_gray" />
        </shape>
    </item>
     <item 
         android:right="1dp" 
         android:bottom="2dp">        
        <shape android:shape="rectangle">
              <solid android:color="@android:color/white"/>
        </shape>
     </item>         
</layer-list> 

自定义选择器:

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

我尝试将选择器应用于整个ListView android:listSelector="@drawable/selector.xml"并将阴影应用于ListView项目android:background="@drawable/shadow.xml"但是在这种情况下,ListView项目将具有阴影但不会对触摸作出反应。

提前谢谢

1 个答案:

答案 0 :(得分:8)

我找到了解决方案。 seletor不出现的原因是Android ListView结构。如果将背景设置为List ItemView,它会与Selector重叠,因此您无法看到它。解决方案是在Click上使ItemView背景透明。

以下是listview_item_shadow.xml

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
              <solid android:color="@android:color/darker_gray" />
        </shape>
    </item>
     <item 
         android:right="1dp" 
         android:bottom="2dp">        
        <shape android:shape="rectangle">
              <solid android:color="@android:color/white"/>
        </shape>
     </item>         
</layer-list>

现在你应该在ItemView的选择器中使用它! - listview_item_backgroundstate.xml 您需要将listview_item_backgroundstate.xml设置为ListView项目的背景

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

最后,您必须将custom_selector.xml设置为ListViewandroid:listSelector="@drawable/custom_selector.xml"

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

欲了解更多信息,请阅读这篇精彩的tutorial