是否可以通过列表选择器将自定义背景应用于每个列表视图项目?
默认选择器指定@android:color/transparent
为了state_focused="false"
情况,但将其更改为某些自定义可绘制对象不会影响未选择的项目。罗曼·盖伊似乎建议在这个答案中 https://stackoverflow.com/questions/2217753/changing-background-color-of-listview-items-on-android/2218270#2218270这是可能的。
我目前通过在每个视图上使用自定义背景并在选择项目/聚焦/任何内容时隐藏它来实现相同的效果,以便显示选择器,但将所有这些都定义在一个地方会更优雅。
作为参考,这是我用来尝试使其工作的选择器:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false"
android:drawable="@drawable/list_item_gradient" />
<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
<item android:state_focused="true" android:state_enabled="false"
android:state_pressed="true"
android:drawable="@drawable/list_selector_background_disabled" />
<item android:state_focused="true" android:state_enabled="false"
android:drawable="@drawable/list_selector_background_disabled" />
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/list_selector_background_transition" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/list_selector_background_transition" />
<item android:state_focused="true"
android:drawable="@drawable/list_selector_background_focus" />
</selector>
这就是我设置选择器的方式:
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:listSelector="@drawable/list_selector_background" />
我自己也曾为此苦恼过,最后终于解决了。正如罗曼·盖伊暗示的那样,还有另一种状态,"android:state_selected"
,您必须使用。使用状态可绘制对象作为列表项的背景,并使用不同的状态可绘制对象listSelector
您的清单中:
list_row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="@drawable/listitem_background"
>
...
</LinearLayout>
listitem_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/android:transparent" />
<item android:drawable="@drawable/listitem_normal" />
</selector>
包含 ListView 的layout.xml:
...
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/listitem_selector"
/>
...
listitem_selector.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/listitem_pressed" />
<item android:state_focused="true" android:drawable="@drawable/listitem_selected" />
</selector>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)