您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)Android如何實現(xiàn)自動輪詢的RecycleView,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
需求:類似醫(yī)院或者商場,大屏幕無限輪播item (廣告詞/廣告圖…),供大家參考,具體內(nèi)容如下
代碼如下
/** * Created by Xia_焱 on 2017/8/20. */public class AutoPollRecyclerView extends RecyclerView { private static final long TIME_AUTO_POLL = 32; AutoPollTask autoPollTask; private boolean running; //標示是否正在自動輪詢 private boolean canRun;//標示是否可以自動輪詢,可在不需要的是否置false public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); autoPollTask = new AutoPollTask(this); } static class AutoPollTask implements Runnable { private final WeakReference<AutoPollRecyclerView> mReference; //使用弱引用持有外部類引用->防止內(nèi)存泄漏 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,recyclerView.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); }}
開啟:如果正在運行,先停止->再開啟
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); }}
Adapter中的代碼如下
@Override public void onBindViewHolder(BaseViewHolder holder, int position) { String data = mData.get(position%mData.size()); holder.setText(R.id.tv_content,data); } @Override public int getItemCount() { return Integer.MAX_VALUE; }
Activity中的代碼
mRecyclerView.setAdapter(adapter); if (true) //保證itemCount的總個數(shù)寬度超過屏幕寬度->自己處理 mRecyclerView.start();
關(guān)于“Android如何實現(xiàn)自動輪詢的RecycleView”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。