SoFunction
Updated on 2025-03-11

Android implements RecycleView for automatic polling

Requirements: Similar to hospitals or shopping malls, large-screen unlimited carousel items (advertising slogans/advertising pictures...), for your reference, the specific content is as follows

The code is as follows

/**
  * Created by Xia_Yan on 2017/8/20.
  */

public class AutoPollRecyclerView extends RecyclerView {
 private static final long TIME_AUTO_POLL = 32;
 AutoPollTask autoPollTask;
 private boolean running; //Sign whether the polling is being automatically private boolean canRun;//Sign whether it can be automatically polled, and whether it can be set to false if it is not needed public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) {
 super(context, attrs);
 autoPollTask = new AutoPollTask(this);
 }
 static class AutoPollTask implements Runnable {
 private final WeakReference<AutoPollRecyclerView> mReference;
 // Use weak references to hold external class references -> Prevent memory leaks public AutoPollTask(AutoPollRecyclerView reference) {
  = new WeakReference<AutoPollRecyclerView>(reference);
 }
 @Override
 public void run() {
 AutoPollRecyclerView recyclerView = ();
 if (recyclerView != null &&  &&) {
 (2, 2);
 (,recyclerView.TIME_AUTO_POLL);
 }
 }
 }
 //Open: If it is running, stop first -> then start 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 (()){
 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 (e);
 }
}

Open: If it is running, stop first-> and then start

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 (()){
 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 (e);
 }
}

The code in Adapter is as follows

@Override
 public void onBindViewHolder(BaseViewHolder holder, int position) {
 String data = (position%());
 (.tv_content,data);
 }
 @Override
 public int getItemCount() {
 return Integer.MAX_VALUE;
 }

Code in Activity

(adapter);
 if (true) //Make sure that the total number of itemCounts exceeds the screen width -> handle it yourself ();

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.