AutoPollRecyclerView.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package com.edufound.reader.cusview;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.view.MotionEvent;
  5. import java.lang.ref.WeakReference;
  6. import androidx.recyclerview.widget.RecyclerView;
  7. import io.reactivex.rxjava3.annotations.Nullable;
  8. public class AutoPollRecyclerView extends RecyclerView {
  9. private static final long TIME_AUTO_POLL = 16;
  10. AutoPollTask autoPollTask;
  11. private boolean running; //标示是否正在自动轮询
  12. private boolean canRun;//标示是否可以自动轮询,可在不需要的是否置false
  13. public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) {
  14. super(context, attrs);
  15. autoPollTask = new AutoPollTask(this);
  16. }
  17. static class AutoPollTask implements Runnable {
  18. private final WeakReference<AutoPollRecyclerView> mReference;
  19. //使用弱引用持有外部类引用->防止内存泄漏
  20. public AutoPollTask(AutoPollRecyclerView reference) {
  21. this.mReference = new WeakReference<AutoPollRecyclerView>(reference);
  22. }
  23. @Override
  24. public void run() {
  25. AutoPollRecyclerView recyclerView = mReference.get();
  26. if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
  27. recyclerView.scrollBy(2, 2);
  28. recyclerView.postDelayed(recyclerView.autoPollTask, recyclerView.TIME_AUTO_POLL);
  29. }
  30. }
  31. }
  32. //开启:如果正在运行,先停止->再开启
  33. public void start() {
  34. if (running)
  35. stop();
  36. canRun = true;
  37. running = true;
  38. postDelayed(autoPollTask, TIME_AUTO_POLL);
  39. }
  40. public void stop() {
  41. running = false;
  42. removeCallbacks(autoPollTask);
  43. }
  44. @Override
  45. public boolean onTouchEvent(MotionEvent e) {
  46. switch (e.getAction()) {
  47. case MotionEvent.ACTION_DOWN:
  48. if (running)
  49. stop();
  50. break;
  51. case MotionEvent.ACTION_UP:
  52. case MotionEvent.ACTION_CANCEL:
  53. case MotionEvent.ACTION_OUTSIDE:
  54. if (canRun)
  55. start();
  56. break;
  57. }
  58. return super.onTouchEvent(e);
  59. }
  60. }