Android - 禁用ListView选择高亮但保留OnClick功能。

5

我希望能够通过代码禁用用户选择行时出现的高亮显示(listSelector),但我不想禁用onClick和enabled设置(仍然要监听点击事件,只是想去掉高亮)。


你使用的是哪个适配器? - Dmitry Guselnikov
一个简单的ArrayAdapter<String>。这会有影响吗? - Abdalrahman Shatou
1
我想要禁用当用户选择一行时出现的高亮显示。-- 为什么?而那些使用箭头键、D-pad等导航您的应用的用户呢?请让您的应用程序能够被所有用户使用,而不仅仅是触摸屏幕的用户。 - CommonsWare
希望下面这段代码能够帮到你:https://dev59.com/O3E85IYBdhLWcg3wLAUV#4075045。 - Dmitry Guselnikov
1
@CommonsWare 好的,我不想支持物理键盘,而且我也不会支持 :) - Abdalrahman Shatou
5个回答

17
在你的ListView XML中,指定android:listSelector="@android:color/transparent"

非常简单且功能有效! - Ahmed Salman Tahir

6

只需创建一个具有透明颜色的可绘制对象,例如:

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

<item android:state_window_focused="false" android:drawable="@android:color/transparent"/>

<!-- 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_disabled_holo_light" />
<item android:state_focused="true"  android:state_enabled="false" android:drawable="@drawable/list_selector_disabled_holo_light" />
<item android:state_focused="true"  android:state_pressed="true" android:drawable="@color/transparent" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@color/transparent" />
<item android:state_focused="true"  android:drawable="@drawable/list_focused_holo" />

</selector>

然后可以通过代码或XML进行设置:

listView.setSelector(R.drawable.my_transparent_selector);

此方法的javadoc文档描述如下:
设置应用于突出显示当前所选项的可绘制对象。
对应的XML属性是:
android:listSelector 您可以操作所有状态,记得还有焦点状态。

从代码中,尼古拉斯,不是 XML。我已经可以使用 listSelector 属性从 XML 处理它了。 - Abdalrahman Shatou
我不知道为什么你需要那样做,所以保留两个文件并对它们进行操作。 - Nicolas Jafelle
不,编辑后它很好用。我使用了某种复选框而不是行高亮。你的答案非常好用。谢谢。 - Abdalrahman Shatou

4
我这样做了:
通过添加两个与 ListView 相关的属性。
android:cacheColorHint="@android:color/transparent"
android:listSelector="@android:color/transparent"

您的ListView 应该如下所示:

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:cacheColorHint="@android:color/transparent"
    android:listSelector="@android:color/transparent">

</ListView>

完成


1
尝试使用以下代码:listview.setSelector(new ColorDrawable(Color.TRANSPARENT));

这对我来说最容易了,谁会采用编程方法,感谢。 - Zhang

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接