You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Spinner的setOnItemSelectedListener未触发问题求助

解决Spinner的OnItemSelectedListener不触发问题

你完全不需要给my_object_item里的每个组件单独设置监听器,问题的根源其实在你的下拉项布局属性上。

问题原因

Spinner内部会自动处理下拉项的点击事件,以此来触发OnItemSelectedListener的回调。但你给根布局LinearLayout设置了android:clickable="true"和android:focusable="true",这两个属性会让根布局直接拦截掉点击事件,导致Spinner无法接收到点击通知,自然就不会触发onItemSelected方法了。

修复方案

只需要去掉根布局的这两个拦截属性即可,修改后的my_object_item.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/item">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/icon"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"/>

</LinearLayout>

额外优化建议

如果想要给下拉项添加点击时的按压反馈效果,可以给根布局加上android:background="?attr/selectableItemBackground",这样既保留了用户友好的交互反馈,又不会影响Spinner的事件传递逻辑。

另外,确保你的SpinnerAdapter中getItem方法返回的MyObject对象是有效的(避免空指针),不过这不是当前回调不触发的直接原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:48:03