RecyclerView实现自动平滑滚动(AutoScrollLoopView)
项目中需要一个Item可以自动循环滚动,既可以实现上下滚动,也可以实现左右滚动,主要在构造
setLayoutManager()时看传入的位置,是水平还是垂直
整体思路:给RecyclerView设置一个最大数,填充数据时对位置取余,然后用Handler发送,调用rv.smoothScrollToPosition(mAnimPosi); 方法,并设置自定义的管理器来控制速度
Adapter的编写
public class IndexLoopAdapter extends RecyclerView.Adapter<IndexLoopAdapter.MyViewHolder> { private List<IndexList.DataBean> dataList; public IndexLoopAdapter(List<IndexList.DataBean> dataList) { this.dataList = dataList; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rv_index, parent, false)); } @Override public void onBindViewHolder(@NonNull IndexLoopAdapter.MyViewHolder holder, int position) { if (dataList.size() != 0) { holder.ivArrow.setVisibility(View.VISIBLE); IndexList.DataBean dataBean = dataList.get(position % dataList.size()); holder.tvPrice.setText(MathUtils.toTwo(dataBean.close / 1000f)); holder.tvName.setText(dataBean.name); holder.tvIncrease.setText(MathUtils.toTwo(dataBean.incrate / 1000f) + "%"); }else { holder.ivArrow.setVisibility(View.INVISIBLE); } } @Override public int getItemCount() { return Integer.MAX_VALUE; } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView tvPrice, tvName, tvIncrease; private ImageView ivArrow; public MyViewHolder(View itemView) { super(itemView); tvPrice = itemView.findViewById(R.id.tvPrice); tvName = itemView.findViewById(R.id.tvName); tvIncrease = itemView.findViewById(R.id.tvIncrease); ivArrow = itemView.findViewById(R.id.ivArrow); } } }
rv.setLayoutManager(new ScrollLinearLayoutManager(getContext())); indexLoopAdapter = new IndexLoopAdapter(indexList); rv.setAdapter(indexLoopAdapter);
定时发送
private Runnable animRun = new Runnable() {
@Override public void run() { if (getUserVisibleHint()) { rvBottom.smoothScrollToPosition(mAnimPosi); mAnimPosi++; } handler.postDelayed(animRun, 3500); } };
布局管理器
public class ScrollLinearLayoutManager extends LinearLayoutManager { private float mTime = 1500; public ScrollLinearLayoutManager(Context context) { super(context); } public ScrollLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } public ScrollLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) { @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { return mTime / displayMetrics.densityDpi; } }; linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } public void setScrollTime(float time) { this.mTime = time; } }