实现效果
看到这个效果,看到很多人用ViewFlipper实现,但是效果并不理想,于是我想到用RecyclerView试试。
主要是监听recyclerView滑动,开始和暂停来控制,废话不多说,上代码。
自定义RecyclerView
public class AutoPollRecyclerViewextends RecyclerView {
private static final long TIME_AUTO_POLL =16;
private static final long TIME_AUTO_POLL_1 =2000;
AutoPollTaskautoPollTask;
AutoPollTask1autoPollTask1;
private int index =0;
private boolean running; //标示是否正在自动轮询
private boolean canRun;//标示是否可以自动轮询,可在不需要的是否置false
private final int mTouchSlop;
public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
// autoPollTask = new AutoPollTask(this);
autoPollTask1 =new AutoPollTask1(this);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
/**
* 持续滑动(走马灯)
*/
static class AutoPollTaskimplements Runnable {
private final WeakReferencemReference;
//使用弱引用持有外部类引用->防止内存泄漏
public AutoPollTask(AutoPollRecyclerView reference) {
this.mReference =new WeakReference(reference);
}
@Override
public void run() {
Log.e("AutoPollRecyclerView", System.currentTimeMillis() +"");
AutoPollRecyclerView recyclerView =mReference.get();
if (recyclerView !=null && recyclerView.running && recyclerView.canRun) {
recyclerView.scrollBy(2, 2);
recyclerView.postDelayed(recyclerView.autoPollTask, recyclerView.TIME_AUTO_POLL);
}
}
}
/***
* 一次只能滑一个item(轮播图)
*/
static class AutoPollTask1implements Runnable {
private final WeakReferencemReference;
//使用弱引用持有外部类引用->防止内存泄漏