1.主要是这个类实现滚动效果
public class AutoPollRecyclerView extends RecyclerView { private static final long TIME_AUTO_POLL = 100; AutoPollTask autoPollTask; private boolean running; //表示是否正在自动轮询 private boolean canRun;//表示是否可以自动轮询 public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); autoPollTask = new AutoPollTask(this); } static class AutoPollTask implements Runnable { private final WeakReference<AutoPollRecyclerView> mReference; //使用弱引用持有外部类引用->防止内存泄漏 public AutoPollTask(AutoPollRecyclerView reference) { this.mReference = new WeakReference<AutoPollRecyclerView>(reference); } @Override public void run() { AutoPollRecyclerView recyclerView = mReference.get(); if (recyclerView != null && recyclerView.running && recyclerView.canRun) { recyclerView.scrollBy(2, 2); recyclerView.postDelayed(recyclerView.autoPollTask, TIME_AUTO_POLL); } } } //开启:如果正在运行,先停止->再开启 public void start() { if (running) stop(); canRun = true; running = true; postDelayed(autoPollTask, TIME_AUTO_POLL); } public void stop() { running = false; removeCallbacks(autoPollTask); } @Override public boolean onTouchEvent(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: if (running) stop(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_OUTSIDE: if (canRun) start(); break; } return super.onTouchEvent(e); } }
2.适配器
public class AdapterItemAuto extends RecyclerView.Adapter<AdapterItemAuto.ViewHolder> { ArrayList<mBean> list; Context context; public AdapterItemAuto(Context context) { this.context = context; } //创建新View,被LayoutManager所调用 @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_main_adapter, viewGroup, false);//布局根据自己需要排版 ViewHolder vh = new ViewHolder(view); return vh; } //将数据与界面进行绑定的操作 @Override public void onBindViewHolder(ViewHolder viewHolder, int position) { mBean item = list.get(position % list.size()); viewHolder.tvName.setText(item.getName()); } //设置数据 public void setItem(ArrayList<mBean> i) { if (i != null && i.size() > 0) { list = i; notifyDataSetChanged(); } } //实现无限循环,默认设置最大值 @Override public int getItemCount() { // return list == null ? 0 : list.size(); return Integer.MAX_VALUE; } //自定义的ViewHolder,持有每个Item的的所有界面元素 class ViewHolder extends RecyclerView.ViewHolder { TextView tvName; ViewHolder(View view) { super(view); tvName = view.findViewById(R.id.tvName); } } }
3.在布局里面引用
<com.XXX.AutoPollRecyclerView android:id="@+id/recycleList" android:layout_width="match_parent" android:layout_height="wrap_content"/>
4.在activity里面调用
LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recycleList.setLayoutManager(layoutManager);// AdapterItemAuto mAdapter = new AdapterItemAuto(this); recycle.setAdapter(mAdapter ); recycleList.start();