我知道在question和this之类的问题中已经多次讨论过这个问题。 但我不得不说这对我不起作用。
我想要实现的是在特殊情况下通过我的CustomAdapter 标记ListView项目。所以,不是通过用户和点击监听器。我有一个工作的解决方案,通过设置一个背景drawable到convertView。
现在我想改变它,让一个选择器做一个工作,这是一个更清洁的解决方案。但我无法让它发挥作用。设置按下项目的行为并设置不同的颜色没有问题。 但在按下该项目后,我无法将其标记为已选中。
我尝试使用listview_item_selector和listview_selector进行不同的组合。我想,我错过了一些非常普遍的东西。这就是为什么我进行设置只是为了弄清楚如何在按下后标记项目。
这是我的list_item_selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@android:color/transparent"/>
<item android:state_selected="true" android:drawable="@android:color/transparent"/>
<item android:drawable="@drawable/state_normal"/>
</selector>
我的listview_selector设置为ListView作为选择器:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/state_pressed"></item>
<item android:state_selected="true" android:drawable="@drawable/selected_item"/>
</selector>
正如我所说state_pressed
正在发挥作用。但state_selected
让我疯狂。
至少我的自定义项目布局:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/listview_item_selector">
<TextView
android:id="@+id/list_tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFEE"/>
<TextView
android:id="@+id/list_tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFEEEE"/>
</LinearLayout>
我很感激任何建议。
答案 0 :(得分:1)
因为你缺少一个状态,你需要将该行标记为已激活并且具有drawable,表示该行是为激活状态选择的
以示例的方式查看我的问题
Showing the current selection in a listview
然后使用
listview.setItemChecked(position,true);