RecyclerView滚动流畅度优化
2019-05-30 本文已影响0人
Ovadyah
方法一:
// Adapter中添加如下代码
public abstract class RecyclerBaseAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected boolean isScrolling = false;
public void setScrolling(boolean scrolling) {
isScrolling = scrolling;
}
}
// 在子Adapter中的onBind里进行控制
public class SubRecyclerViewAdapter extends BaseRecyclerViewAdapter<DataGuardRanking> {
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
RecyclerViewHolder holder = (RecyclerViewHolder) viewHolder;
if (!TextUtils.isEmpty(data.getAvatarUrl()) && !isScrolling) {
// 加载跟新数据
} else {
holder.avatarImg.setImageResource(占位图);
}
super.onBindViewHolder(holder, position);
}
}
// 外部监听
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// State的三种状态:SCROLL_STATE_IDLE(静止)、SCROLL_STATE_DRAGGING(上升)、SCROLL_STATE_SETTLING(下落)
if (newState == SCROLL_STATE_IDLE) { // 滚动静止时才加载图片资源,极大提升流畅度
mRecyclerViewAdapter.setScrolling(false);
//简单的形式可以使用 notify调用后onBindViewHolder会响应调用
//mRecyclerViewAdapter.notifyDataSetChanged();
} else {
mRecyclerViewAdapter.setScrolling(true);
}
super.onScrollStateChanged(recyclerView, newState);
}
});
方法二:
使用GestureDetector.OnGestureListener监听
public interface OnGestureListener {
boolean onDown(MotionEvent var1);
void onShowPress(MotionEvent var1);
boolean onSingleTapUp(MotionEvent var1);
boolean onScroll(MotionEvent var1, MotionEvent var2, float var3, float var4);
void onLongPress(MotionEvent var1);
boolean onFling(MotionEvent var1, MotionEvent var2, float var3, float var4)
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
if(Math.abs(v1) > 4000){
mAdapter.setScrolling(true);
}
return false;
}
onScrolled方法的作用,如果快速的在屏幕上向下或向上滑动,onFling可以监听到v1大于4000,并且onScrollStateChanged的RecyclerView.SCROLL_STATE_IDLE也会有监听,所以加一个额外条件,如果列表没有任何滚动,则不做任何操作
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(dy != 0){
scrlled = true;
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
// The RecyclerView is not currently scrolling.
case RecyclerView.SCROLL_STATE_IDLE:
if(mAdapter.getScrolling() && scrlled) {
//对于滚动不加载图片的尝试
mAdapter.setScrolling(false);
mAdapter.notifyDataSetChanged();
}
scrlled = false;
break;
}
super.onScrollStateChanged(recyclerView, newState);
}