RecyclerView定位到指定位置

xiaoxiao2021-02-27  209

UI需求点击列表某个控件需要RecyclerView定位到特定的位置

实现该效果是基于一个前提,目标view需要在屏幕上可见,不可见区域的view马上就会被回收掉了或者放到缓存区域里

核心代码如下

RecyclerView.ViewHolder vh=recyclerView.findViewHolderForAdapterPosition(position); if (vh != null) { View view = vh.itemView; int [] location = new int[2]; //获取屏幕上的真实坐标 view.getLocationInWindow(location); int tibar= getBarHeight();//自己界面的title高度 int dy = 0; if (location[1] > tibar) { //向上滑动 dy = location[1] - tibar; } else if (location[1] < 0){ //向下滑动 dy = -(tibar - location[1]); } else if (location[1] < tibar){ //向下滑动 dy = -(tibar - location[1]); } recyclerView.smoothScrollBy(0, dy); } else { //普通方式 recyclerView.scrollVerticallyToPosition(position); }

第2种方式简单粗暴

可以直接滑动到指定的位置,缺点是不够平滑 mLayoutManager = mRecyclerView.getLayoutManager(); mLayoutManager.scrollToPositionWithOffset(pos, 0);

转载请注明原文地址: https://www.6miu.com/read-9682.html

最新回复(0)