zoukankan      html  css  js  c++  java
  • android RecyclerView smoothScrollToPosition 每次都能滚动到顶部

    直接使用 smoothScrollToPosition(position) 时,如果要定位的数据在集合下半部分,则滚动结束后,需要显示的数据是在手机界面地步

    可以使用 ((LinearLayoutManager) ((RecyclerView)getView(R.id.rv)).getLayoutManager()).scrollToPositionWithOffset(position, 0) 达到每次滚动结束,数据都是在顶部显示,但是数据不是平滑滚动的。

    如果要实现不论哪种情况,都能让数据平滑滚动到顶部显示,需要重写 LinearLayoutManager

    1,覆写 LinearSmoothScroller

    public class TopLinearSmoothScroller extends LinearSmoothScroller {
        public TopLinearSmoothScroller(Context context) {
            super(context);
        }
    
        @Override
        public int getVerticalSnapPreference() {
            return SNAP_TO_START;
        }
    }

    2,重写 recyclerview.LinearLayoutManager 的 smoothScrollToPosition 方法

    TopLinearSmoothScroller scroller = new TopLinearSmoothScroller(rv.getContext());
    LinearLayoutManager layoutManager = new LinearLayoutManager(context) {
        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
            super.smoothScrollToPosition(recyclerView, state, position);
            scroller.setTargetPosition(position);
            startSmoothScroll(scroller);
        }
    };
    rv.setLayoutManager(layoutManager);

    3,最后调用 smoothScrollToPosition 即可

    rv.smoothScrollToPosition(position);
  • 相关阅读:
    matlab中pcolorh函数作用
    Matlab中^2和.^2的区别
    Python实战项目网络爬虫 之 爬取小说吧小说正文
    如何查看mysql数据库的端口
    template模板找不到
    templates模板使用变量,显示红色报错
    多线程案例1:奇偶交替输出
    idea配置classpath,后面文件找不到,显示红色
    idea创建各种类型项目
    tomcat修改端口
  • 原文地址:https://www.cnblogs.com/ice5/p/15291256.html
Copyright © 2011-2022 走看看