在开发Android应用的过程中,ViewPager有时候需要自动播放的功能,今天就介绍一下自动播放功能的实现,直接上代码:
// viewpager auto play
private static final long ANIM_VIEWPAGER_DELAY = 3000; private Handler h = new Handler();
private Runnable animateViewPager = new Runnable() {
public void run() {
if (mViewList.size() > 0) {
mViewPager.setCurrentItem((mViewPager.getCurrentItem() + 1)
% mViewList.size(), true);
h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
}
}; @Override
public void onPause() {
super.onPause();
if (h != null) {
h.removeCallbacks(animateViewPager);
}
} @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (h != null) {
h.removeCallbacks(animateViewPager);
}
}
if (ev.getAction() == MotionEvent.ACTION_UP) {
h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
return super.dispatchTouchEvent(ev);
} @Override
protected void onResume() {
super.onResume();
h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}