You need to enable JavaScript to run this app. Android自定义ListView setOnItemClickListener点击仅背景变灰无响应
优惠活动
大模型
产品
解决方案
定价
更多

Android自定义ListView setOnItemClickListener点击仅背景变灰无响应

ListView点击仅显示按压效果、不触发OnItemClick的修复方案

核心根因

事件分发链路被自定义属性拦截,子项布局直接消费了触摸事件,无法冒泡到ListView层触发预设的点击回调,仅能展示系统自带的按压态背景反馈。

逐点修正操作

1. 调整列表项行布局的拦截属性

打开列表项对应的布局文件(即适配器中inflate的R.layout.activity_kiosker_oppsett),删除根布局上的两个多余属性:

  • 删除android:focusable="true"
  • 删除android:clickable="true"

注意:保留android:background="?android:attr/selectableItemBackground"即可,该属性本身不会拦截事件,无需额外给根布局设置clickable就能保留点击时的深灰色按压反馈。
修正后的根布局参考代码:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:background="?android:attr/selectableItemBackground">

额外优化:原布局中给RelativeLayout设置的android:orientation="vertical"是无效属性,RelativeLayout不支持该属性,可直接删除减少冗余代码。

2. 移除主页面根布局的事件拦截属性

打开主页面布局文件,删除最外层RelativeLayout上的android:clickable="true"属性。该属性会让整个页面的根布局直接消费触摸事件,进一步干扰列表的事件分发流程,修正后的根布局参考代码:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

3. 优化自定义适配器的冗余实现

原有适配器代码不直接导致点击失效,但存在内存浪费、逻辑冗余的问题,可同步修正:

  • 删掉类中重复声明的列表变量,直接通过构造函数传入数据
  • 给getView方法加上convertView复用逻辑,避免每次创建新布局视图
    修正后的适配器参考代码:
class ListViewAdapterK(
    private val activity: Activity,
    private val dataList: ArrayList<String>
) : BaseAdapter() {

    override fun getCount(): Int = dataList.size

    override fun getItem(position: Int): Any = dataList[position]

    override fun getItemId(position: Int): Long = position.toLong()

    @SuppressLint("ViewHolder")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        // 复用已有的视图,避免重复inflate
        val itemView = convertView ?: LayoutInflater.from(activity)
            .inflate(R.layout.activity_kiosker_oppsett, parent, false)
        itemView.findViewById<TextView>(R.id.oppsett).text = dataList[position]
        return itemView
    }
}

4. 校验点击监听的绑定逻辑

确认kioskListe.setOnItemClickListener的绑定时机在适配器设置完成、列表数据加载完成之后,不存在绑定监听器后重新设置适配器、导致原有监听器被覆盖的情况。


内容的提问来源于stack exchange,提问作者HansO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.08 00:36:07