0


Android RecyclerView定位到指定的item并置顶

具体项目开发中,会有这样的需求:进入到一个列表(含RecyclerView)页面以后,定位到指定的一个item,并且将此item显示在顶部。

说到RecyclerView的item定位,我们优先想到的可能是以下2种方式:

  1. scrollToPosition(int position);
  2. smoothScrollToPosition(int position);

第一个方法scrollToPosition(position)是定位到指定item,是瞬间显示在页面上,用户可见的范围。位置不固定。
第二个方法与第一个不同的是平滑到你指定的item,而scrollToPosition是瞬间定位到指定位置。

这2个方法,虽都定位到指定的item,但是都没有将target item置顶展示。

此时,我们可以用到LinearSmoothScroller类,LinearSmoothScroller的作用是可以让RecyclerView指定的item滑动到页面可见的范围之内。

1.实现原理:重写LinearSmoothScroller的calculateSpeedPerPixel()方法,重新设置滑动的速度。

当新建LinearSmoothScroller对象时,已经计算好了滚动的速度,滚动速度和像素密度有关,MILLISECONDS_PER_PX 越大滚动越慢。

  1. public class LinearTopSmoothScroller extends LinearSmoothScroller {
  2. /**
  3. * MILLISECONDS_PER_INCH 值越大滚动越慢
  4. */
  5. private float MILLISECONDS_PER_INCH = 0.03f;
  6. private final Context context;
  7. /**
  8. * @param context context
  9. * @param needFast 是否需要快速滑动
  10. */
  11. public LinearTopSmoothScroller(Context context, boolean needFast) {
  12. super(context);
  13. this.context = context;
  14. if (needFast) {
  15. setScrollFast();
  16. } else {
  17. setScrollSlowly();
  18. }
  19. }
  20. @Override
  21. protected int getVerticalSnapPreference() {
  22. return SNAP_TO_START;
  23. }
  24. @Override
  25. protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
  26. //return super.calculateSpeedPerPixel(displayMetrics);
  27. setScrollSlowly();
  28. return MILLISECONDS_PER_INCH / displayMetrics.density;
  29. }
  30. public void setScrollSlowly() {
  31. //建议不同分辨率设备上的滑动速度相同
  32. //0.3f可以根据不同自己的需求进行更改
  33. MILLISECONDS_PER_INCH = context.getResources().getDisplayMetrics().density * 0.3f;
  34. }
  35. public void setScrollFast() {
  36. MILLISECONDS_PER_INCH = context.getResources().getDisplayMetrics().density * 0.03f;
  37. }
  38. }

2.如何调用:

  1. /**
  2. * 指定item并置顶
  3. *
  4. * @param position item索引
  5. */
  6. public void scrollItemToTop(int position) {
  7. LinearTopSmoothScroller smoothScroller = new LinearTopSmoothScroller(mContext,false);
  8. smoothScroller.setTargetPosition(position);
  9. mLayoutManager.startSmoothScroll(smoothScroller);
  10. }
  1. 具体到需求代码中:
  2. // 渐渐上滑定位到评论区域,如果页面是网络请求的数据,则可以等页面展示结束再滑动。
  3. new Handler().postDelayed(new Runnable() {
  4. @Override
  5. public void run() {
  6. // position根据自己的需求传入即可
  7. binding.baseRecyclerView.scrollItemToTop(position);
  8. }
  9. }, 200);

本文转载自: https://blog.csdn.net/u010231454/article/details/122875371
版权归原作者 碧水逍遥 所有, 如有侵权,请联系我们删除。

“Android RecyclerView定位到指定的item并置顶”的评论:

还没有评论