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

Android:RecyclerView选中Spinner后如何阻止EditText获焦滚动?

解决RecyclerView选中末尾项Spinner后自动滚动到EditText的问题

我太懂这种糟心的体验了——好不容易滚到列表末尾点个Spinner,结果页面直接跳回顶部,还自动聚焦到第一个EditText上。这种问题本质是系统在Spinner弹出对话框时,会自动寻找页面上可聚焦的View(也就是你的EditText),进而触发RecyclerView滚动到获焦元素的位置。给你几个实用的解决办法:

方法一:让Spinner优先获取焦点

直接在XML里给每个Spinner添加焦点属性,让Spinner被点击时先拿到焦点,不让系统去“搜寻”其他可聚焦View:

android:focusable="true"
android:focusableInTouchMode="true"

比如你的spinner_SelectSub1可以修改成这样:

<Spinner android:id="@+id/spinner_SelectSub1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:paddingStart="@dimen/padding" 
    android:paddingEnd="@dimen/padding" 
    android:background="@drawable/ic_spinner_dropdown" 
    android:textAlignment="center" 
    android:spinnerMode="dialog"
    android:focusable="true"
    android:focusableInTouchMode="true" />

另外两个Spinner也照这个方式添加属性就行,这个方法最简单,大概率能直接解决问题。

方法二:阻止RecyclerView的自动聚焦滚动

如果方法一没效果,试试在初始化RecyclerView的代码里加上这句,直接禁用RecyclerView因子View获焦而触发的滚动:

recyclerView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

注意:这个设置会让所有子View默认无法获取焦点,如果你的EditText需要正常输入,得手动在需要的时候给EditText设置焦点,比如:

holder.et_comment.requestFocus();

方法三:手动控制EditText的焦点行为

要是上面两种方法都不适用,还可以从EditText入手优化。首先确保你的EditText已经有android:focusableInTouchMode="true"(你的XML里已经加了),然后在Adapter的onBindViewHolder方法里手动管控焦点:

@Override
public void onBindViewHolder(YourViewHolder holder, int position) {
    // 你的其他数据绑定逻辑
    // 只有用户主动点击EditText时才让它获焦
    holder.et_comment.setOnTouchListener((v, event) -> {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            holder.et_comment.requestFocus();
        }
        return false;
    });
    // 非用户当前点击的EditText,主动清除焦点
    if (holder.getAdapterPosition() != currentFocusPosition) {
        holder.et_comment.clearFocus();
    }
}

这里的currentFocusPosition可以用来记录用户当前点击的EditText所在位置,避免其他EditText乱获焦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:17:28