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

RecyclerView项获焦跳转求助:文本选中时列表跳至顶部

解决RecyclerView中选中文本时列表跳顶部的问题

我之前也踩过这个坑!问题根源确实是焦点争夺——当你给TextView开启setTextIsSelectable(true)后,文本选中操作会触发TextView请求焦点,而RecyclerView默认会自动滚动到获取焦点的Item位置,这就导致了莫名其妙跳转到顶部的现象。下面给你几个亲测有效的解决办法:

方案一:自定义TextView,阻止焦点请求

最稳妥的方式是自定义一个TextView,重写焦点相关的方法,让它既能保留文本选中功能,又不会请求焦点:

public class SelectableNonFocusableTextView extends AppCompatTextView {
    public SelectableNonFocusableTextView(Context context) {
        super(context);
        setupView();
    }

    public SelectableNonFocusableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setupView();
    }

    public SelectableNonFocusableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setupView();
    }

    private void setupView() {
        setTextIsSelectable(true);
    }

    @Override
    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
        // 拒绝焦点请求,避免RecyclerView自动滚动
        return false;
    }

    @Override
    public boolean isFocusable() {
        return false;
    }

    @Override
    public boolean isFocusableInTouchMode() {
        return false;
    }
}

之后在你的RecyclerView Item布局里,用这个自定义TextView替换原来的TextView即可,完美保留选中文本的功能,同时不会触发滚动。

方案二:重写RecyclerView布局管理器,拦截焦点滚动

如果你不想自定义TextView,也可以在RecyclerView的布局管理器上动手脚,拦截它自动滚动到焦点Item的行为。以LinearLayoutManager为例:

LinearLayoutManager layoutManager = new LinearLayoutManager(this) {
    @Override
    public boolean requestChildFocus(View child, View focused) {
        // 拦截焦点滚动请求,返回true表示已处理,不会触发默认滚动
        return true;
    }
};
recyclerView.setLayoutManager(layoutManager);

如果用的是GridLayoutManager或者其他布局管理器,思路完全一致,重写requestChildFocus方法返回true就行。

方案三:XML属性直接禁用TextView焦点(需测试)

你也可以直接在XML里给TextView设置焦点相关属性:

<TextView
    android:id="@+id/tv_item_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textIsSelectable="true"
    android:focusable="false"
    android:focusableInTouchMode="false"/>

不过要注意,部分Android版本可能会因为禁用焦点导致文本选中功能异常,所以这个方法建议先在目标设备上测试验证,如果没问题再用。


内容的提问来源于stack exchange,提问作者Iván Ferrant

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:47:37