Android实现自动轮询的RecycleView
需求:类似医院或者商场,大屏幕无限轮播item(广告词/广告图…),供大家参考,具体内容如下
代码如下
/**
*CreatedbyXia_焱on2017/8/20.
*/
publicclassAutoPollRecyclerViewextendsRecyclerView{
privatestaticfinallongTIME_AUTO_POLL=32;
AutoPollTaskautoPollTask;
privatebooleanrunning;//标示是否正在自动轮询
privatebooleancanRun;//标示是否可以自动轮询,可在不需要的是否置false
publicAutoPollRecyclerView(Contextcontext,@NullableAttributeSetattrs){
super(context,attrs);
autoPollTask=newAutoPollTask(this);
}
staticclassAutoPollTaskimplementsRunnable{
privatefinalWeakReferencemReference;
//使用弱引用持有外部类引用->防止内存泄漏
publicAutoPollTask(AutoPollRecyclerViewreference){
this.mReference=newWeakReference(reference);
}
@Override
publicvoidrun(){
AutoPollRecyclerViewrecyclerView=mReference.get();
if(recyclerView!=null&&recyclerView.running&&recyclerView.canRun){
recyclerView.scrollBy(2,2);
recyclerView.postDelayed(recyclerView.autoPollTask,recyclerView.TIME_AUTO_POLL);
}
}
}
//开启:如果正在运行,先停止->再开启
publicvoidstart(){
if(running)
stop();
canRun=true;
running=true;
postDelayed(autoPollTask,TIME_AUTO_POLL);
}
publicvoidstop(){
running=false;
removeCallbacks(autoPollTask);
}
@Override
publicbooleanonTouchEvent(MotionEvente){
switch(e.getAction()){
caseMotionEvent.ACTION_DOWN:
if(running)
stop();
break;
caseMotionEvent.ACTION_UP:
caseMotionEvent.ACTION_CANCEL:
caseMotionEvent.ACTION_OUTSIDE:
if(canRun)
start();
break;
}
returnsuper.onTouchEvent(e);
}
}
开启:如果正在运行,先停止->再开启
publicvoidstart(){
if(running)
stop();
canRun=true;
running=true;
postDelayed(autoPollTask,TIME_AUTO_POLL);
}
publicvoidstop(){
running=false;
removeCallbacks(autoPollTask);
}
@Override
publicbooleanonTouchEvent(MotionEvente){
switch(e.getAction()){
caseMotionEvent.ACTION_DOWN:
if(running)
stop();
break;
caseMotionEvent.ACTION_UP:
caseMotionEvent.ACTION_CANCEL:
caseMotionEvent.ACTION_OUTSIDE:
if(canRun)
start();
break;
}
returnsuper.onTouchEvent(e);
}
}
Adapter中的代码如下
@Override
publicvoidonBindViewHolder(BaseViewHolderholder,intposition){
Stringdata=mData.get(position%mData.size());
holder.setText(R.id.tv_content,data);
}
@Override
publicintgetItemCount(){
returnInteger.MAX_VALUE;
}
Activity中的代码
mRecyclerView.setAdapter(adapter); if(true)//保证itemCount的总个数宽度超过屏幕宽度->自己处理 mRecyclerView.start();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。