android – RecyclerVIew自动滚动显示所有元素,如新闻Feed等,
作者:互联网
如何平滑地自动滚动RecyclerView,以便用户可以看到RecyclerView的所有元素并从头开始再次滚动 – 如同News Feed等.
我知道smoothScrollToPosition()和scrollToPosition(),但它们最终会滚动到最后一个元素.
我希望RecyclerView能够动画并且移动缓慢.
解决方法:
只是为了改善答案,它是自动滚动无限和平滑动画.
final int speedScroll = 1200;
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
boolean flag = true;
@Override
public void run() {
if(count < adapter.getItemCount()){
if(count==adapter.getItemCount()-1){
flag = false;
}else if(count == 0){
flag = true;
}
if(flag) count++;
else count--;
recyclerView.smoothScrollToPosition(count);
handler.postDelayed(this,speedScroll);
}
}
};
handler.postDelayed(runnable,speedScroll);
这正是您的答案,但如果链接到更流畅的动画,则使用LayoutManager
recyclerView.setLayoutManager(new CustomLinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
控制动画改变MILLISECONDS_PER_INCH值.
public class CustomLinearLayoutManager extends LinearLayoutManager {
public CustomLinearLayoutManager(Context context) {
super(context);
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
final LinearSmoothScroller linearSmoothScroller =
new LinearSmoothScroller(recyclerView.getContext()) {
private static final float MILLISECONDS_PER_INCH = 200f;
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return CustomLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected float calculateSpeedPerPixel
(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
}
};
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
}
标签:recycler-adapter,android,android-recyclerview,scroll 来源: https://codeday.me/bug/20190930/1836652.html