RecyclerView存在大量Item時,當滾到底部時快速滑到頂部
阿新 • • 發佈:2019-02-06
在使用RecyclerView展示圖片或者其他資訊時,往往需要展示很多的Item,當滾到底部時又想回到頂部,如果一點一點的向上劃去比較麻煩,而且使用者體驗不好。因此新增一個快速回到頂部的按鈕是很有必要的,並且剛開始的時候這個按鈕是隱藏的,當滑動超過超過一屏的時候才會出現,在滑動的過程中也是不會出現的。很多類似的專案都會使用到,但是如何在快速回到頂部的過程中不出現卡頓,體現的很是流暢,這點很重要。下面是我根據網上的方法自己修改的一個可以快速回到頂部的類,在此做一下備註,以便日後檢視:
- 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;
/**
* Author: aaa
* Date: 2017/3/16 11:16.
* 快速回到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);