栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

RecyclerView滑动到指定位置

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

RecyclerView滑动到指定位置

需求 将recyclerview滑动到指定位置 且该位置为第一个可见位置

方式一 LayoutManager.scrollToPositionWithOffset

int toPosition 
((LinearLayoutManager)rvSaleMonth.getLayoutManager()).scrollToPositionWithOffset(toPosition, 0);

方式二 RecyclerView.scrollToPosition RecyclerView.scrollBy RecyclerView.post

private void moveToPosition(int toPosition){
 int firstPosition ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).findFirstVisibleItemPosition();
 int lastPostition ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).findLastVisibleItemPosition();
 if (toPosition firstPosition){
 rvSaleMonth.scrollToPosition(toPosition);
 }else if (toPosition lastPostition){
 int top rvSaleMonth.getChildAt(toPosition - firstPosition).getTop();
 rvSaleMonth.scrollBy(0, top);
 }else {
 //先滑动到可见 需要二次滑动
 rvSaleMonth.scrollToPosition(toPosition);
 rvSaleMonth.post(() - {
 //进行第二次滑动
 int first ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).findFirstVisibleItemPosition();
 View childView rvSaleMonth.getChildAt(toPosition - first);
 if (childView ! null){
 int top childView.getTop();
 rvSaleMonth.scrollBy(0, top);
 }

1 要滑动的位置比可见位置小 则直接scrollToPosition即可

2 滑动位置在可见位置区间内 则需要根据子view和父view顶部间距离进行移动

3 要滑动的位置比可见位置大 则需要先通过scrollToPosition移至可见位置 位置非顶部 再根据子view和父view顶部间距离进行移动

4 由于scrollToPosition不触发onScrollListener 不能通过监听滑动状态来进行 3 中的二次滑动 但由于RecyclerView滑动结束才执行post的run方法 可以在run方法中进行二次滑动

5 另外补充一下smoothScrollToPosition方法是回触发OnScrollListener的 使用该方法进行滑动时可以通过监听状态进行二次滑动

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/266950.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号