RecyclerView 滑动到指定下标、快速导航

需求

城市列表快速定位:通过右边的地区字母快速导航到特定位置
通讯录的快速定位

分析思路

网上查看的文章说:分三种情况,即屏幕上方、屏幕中、屏幕下方;分别处理代码逻辑;
实际分析后发现完全可以使用比较简单的方式实现:

默认API

RecyclerView 提供了3种方法用于滑动到特定位置的API

API 区别
scrollBy(int x, int y) 根据x、y轴的距离,滑动
smoothScrollToPosition(int position) 平滑滚动到特定 position
scrollToPosition(int position) 滚动到特定position

但是通过具体代码的实践:均不能达到预期效果

  • scrollBy() 方法可以通计算 child.getTop() 获得其需要滑动的距离,但是如果 child 在屏幕之外,需要的 child 未创建,无法获得
  • scrollToPosition(int position)smoothScrollToPosition(int position)方法可以通过 position 滑动到特定下标,但是有个特点:
    • position < firstViewItemPosition,则列表向下滚动 目标 position 滚动到顶部位置
    • firstVisibleItemPosition < position < lastVisibleItemPosition :列表不会滚动
    • position > lastVisibleItemPosition : 列表向上滚动, 目标position 滚动到屏幕底部位置

可见均不能达到我们的预期;
那我们去分析一下 smoothScrollToPosition() 的具体实现,看下我们是否可以干预一下其滚动规则

源码分析

// RecyclerView.java

public void smoothScrollToPosition(int position) {
    if (mLayoutFrozen) {
        return;
    }
    if (mLayout == null) {
        Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
                "Call setLayoutManager with a non-null argument.");
        return;
    }
    
    // @VisibleForTesting LayoutManager mLayout;
    // 这里调用了 LayouManager 去实现滚动。
    mLayout.smoothScrollToPosition(this, mState, position);
}
// LayoutManager 类

public void smoothScrollToPosition(RecyclerView recyclerView, State state, int position) {
    // LayoutManager 中并没有实现代码,而是由 我们设置的 其子类来具体的实现的
    Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling");
}
// LinearLayoutManager 类

@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
    // 滚动控制器
    LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext());
    // 设置滚动目标 position
    linearSmoothScroller.setTargetPosition(position);
    // 由 LineraManager 调用
    startSmoothScroll(linearSmoothScroller);
}
// LayoutManager 类

public void startSmoothScroll(SmoothScroller smoothScroller) {
    
    // 数据以及状态的校验
    if (mSmoothScroller != null && smoothScroller != mSmoothScroller && mSmoothScroller.isRunning()) {
        mSmoothScroller.stop();
    }
    mSmoothScroller = smoothScroller;
    
    // 触发滚动
    mSmoothScroller.start(mRecyclerView, this);
}

到这里,我们可以发现,RecyclerView 的滚动触发是由 LayoutManager 调用,其控制器的定义是由具体的 Manager 来设置;

继续来分析 SmoothScroller 的源码

// 抽象类
public static abstract class SmoothScroller{}
/**
 * 线性平滑滚动控制器。
 */
public class LinearSmoothScroller extends RecyclerView.SmoothScroller {
    
    // 其他源码 ...
    
    /**
     * 当滚动到子视图时,这种方法定义了:child 与 parent 是否应该左对齐或右对齐。
     * 
     * When scrolling towards a child view, this method defines whether we should align the left
     * or the right edge of the child with the parent RecyclerView.
     *
     * @return SNAP_TO_START, SNAP_TO_END or SNAP_TO_ANY;
     */
    protected int getHorizontalSnapPreference() {
        return mTargetVector == null || mTargetVector.x == 0 ? SNAP_TO_ANY :
                mTargetVector.x > 0 ? SNAP_TO_END : SNAP_TO_START;
    }

    /**
     * 当滚动到子视图时,这种方法定义了:child 与 parent 是否应该顶对齐或底对齐。
     * 
     * When scrolling towards a child view, this method defines whether we should align the top
     * or the bottom edge of the child with the parent RecyclerView.
     *
     * @return SNAP_TO_START, SNAP_TO_END or SNAP_TO_ANY;
     */
    protected int getVerticalSnapPreference() {
        return mTargetVector == null || mTargetVector.y == 0 ? SNAP_TO_ANY :
                mTargetVector.y > 0 ? SNAP_TO_END : SNAP_TO_START;
    }
    
    // 其他源码 ... 
}

通过注释就可以看出:上面两个方法控制了 childView 的对齐方式,且是 protected 修饰的方法,那我们完全可以通过自定义返回对齐方式

具体实现

// 定义滚动控制器
private LinearSmoothScroller smoothScroller;
smoothScroller= new LinearSmoothScroller(inflater.getContext()) {

    // 这里考虑的是垂直列表
    @Override
    protected int getVerticalSnapPreference() {
        
        // 固定返回顶对齐方式
        return SNAP_TO_START;
    }
};

// 设置滚动目标 position
smoothScroller.setTargetPosition(index);
// 主动触发滚动
recyclerView.getLayoutManager().startSmoothScroll(smoothScroller);

至此,即可实现文头的需求方案;

效果图

recyclerView导航效果图.gif
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容