前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android实现自动轮询的RecycleView

Android实现自动轮询的RecycleView

作者头像
砸漏
发布2020-10-16 10:46:32
4290
发布2020-10-16 10:46:32
举报
文章被收录于专栏:恩蓝脚本

需求:类似医院或者商场,大屏幕无限轮播item (广告词/广告图…),供大家参考,具体内容如下

代码如下

代码语言:javascript
复制
/**
 * 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;
 //使用弱引用持有外部类引用- 防止内存泄漏
 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);
 }
}

开启:如果正在运行,先停止- 再开启

代码语言:javascript
复制
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中的代码如下

代码语言:javascript
复制
@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中的代码

代码语言:javascript
复制
mRecyclerView.setAdapter(adapter);
 if (true) //保证itemCount的总个数宽度超过屏幕宽度- 自己处理
 mRecyclerView.start();

以上就是本文的全部内容,希望对大家的学习有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档