直播平臺原始碼,迴圈滾動RecyclerView的實現
阿新 • • 發佈:2022-11-29
直播平臺原始碼,迴圈滾動RecyclerView的實現
public class AutoRecyclerView extends RecyclerView {
private static final long TIME_AUTO_POLL = 16;
private final AutoPollTask autoPollTask;
private boolean running; //表示是否正在自動輪詢
private boolean canRun;//表示是否可以自動輪詢
public AutoRecyclerView(@NonNull Context context) {
super(context);
autoPollTask = new AutoPollTask(this);
}
public AutoRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
autoPollTask = new AutoPollTask(this);
}
public AutoRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
autoPollTask = new AutoPollTask(this);
}
private static class AutoPollTask implements Runnable {
private final WeakReference<AutoRecyclerView> mReference;
//使用弱引用持有外部類引用->防止記憶體洩漏
public AutoPollTask(AutoRecyclerView reference) {
this.mReference = new WeakReference<>(reference);
}
@Override
public void run() {
AutoRecyclerView recyclerView = mReference.get();
if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
//水平移動
recyclerView.scrollBy(2, 0);
//豎直移動
//recyclerView.scrollBy(0, 2);
recyclerView.postOnAnimationDelayed(recyclerView.autoPollTask, TIME_AUTO_POLL);
}
}
}
//開啟:如果正在執行,先停止->再開啟
private void start() {
if (running)
stop();
canRun = true;
running = true;
postDelayed(autoPollTask, TIME_AUTO_POLL);
}
private void stop() {
running = false;
removeCallbacks(autoPollTask);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return true;
}
public void startAutoScrolling(){
if (running){
return;
}
start();
}
public void stopAutoScrolling(){
stop();
}
public boolean isAutoScrolling(){
return running;
}
}
以上就是直播平臺原始碼,迴圈滾動RecyclerView的實現, 更多內容歡迎關注之後的文章