需求:类似医院或者商场,大屏幕无限轮播item (广告词/广告图…),供大家参考,具体内容如下
代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
/** * 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); } } |
开启:如果正在运行,先停止->再开启
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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中的代码如下
1
2
3
4
5
6
7
8
9
|
@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中的代码
1
2
3
|
mRecyclerView.setAdapter(adapter); if ( true ) //保证itemCount的总个数宽度超过屏幕宽度->自己处理 mRecyclerView.start(); |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/MacaoPark/article/details/102213937