标签:android
在使用RecyclerView展示图片或者其他信息时,往往需要展示很多的Item,当滚到底部时又想回到顶部,如果一点一点的向上划去比较麻烦,而且用户体验不好。因此添加一个快速回到顶部的按钮是很有必要的,并且刚开始的时候这个按钮是隐藏的,当滑动超过超过一屏的时候才会出现,在滑动的过程中也是不会出现的。很多类似的项目都会使用到,但是如何在快速回到顶部的过程中不出现卡顿,体现的很是流畅,这点很重要。下面是我根据网上的方法自己修改的一个可以快速回到顶部的类,在此做一下备注,以便日后查看:
1.FastScrollManger.java
import android.content.Context; import android.graphics.PointF; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.RecyclerView; import android.util.DisplayMetrics; /** * 快速回到RecyclerView 的顶部,不会出现卡顿 */ public class FastScrollManger extends LinearLayoutManager { public FastScrollLinearLayoutManager(Context context) { super(context); } public FastScrollLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) { @Override public PointF computeScrollVectorForPosition(int targetPosition) { return FastScrollLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition); } //控制速度。 @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { return super.calculateSpeedPerPixel(displayMetrics); } @Override protected int calculateTimeForScrolling(int dx) { if (dx > 3000) { dx = 3000; } int time = super.calculateTimeForScrolling(dx); return time; } }; linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } }
2.使用
mRecyclerView = (RecyclerView) findViewById(R.id.activity_recyclerview); LinearLayoutManager layout = new FastScrollManager(CustomActivity.this, LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(layout);//竖直放置 ... mRecyclerView.setAdapter(mMyAdapter); mRecyclerView.addOnScrollListener(new MyRecyclerViewScrollListener());
3.控制显示与隐藏
//滑动监听 private class MyRecyclerViewScrollListener extends RecyclerView.OnScrollListener { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); int firstVisibleItemPosition = manager.findFirstVisibleItemPosition(); // 当不滚动时 if (newState == RecyclerView.SCROLL_STATE_IDLE) { // 判断是否滚动超过一屏 if (firstVisibleItemPosition == 0) { mImageViewRebackTop.setVisibility(View.INVISIBLE); } else { mImageViewRebackTop.setVisibility(View.VISIBLE); } } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中 mImageViewRebackTop.setVisibility(View.INVISIBLE); } } }
4.点击回到顶部按钮的时候,回到顶部
mRecyclerView.smoothScrollToPosition(0);
附:执着的念想~
本文出自 “梁肖技术中心” 博客,请务必保留此出处http://liangxiao.blog.51cto.com/3626612/1949249
Android Studio - 第四十三期 RecyclerView存在大量Item时,当滚到底部时快速滑到顶部
标签:android
原文地址:http://liangxiao.blog.51cto.com/3626612/1949249