我们实现轮播图效果,大部分都是使用viewpager实现,但是要实现无限循环就要动动脑子了,比如我就是5张图,那么要实现循环播放的话,该怎么实现,我们都知道viewpager最终的数据显示是通过adapter,而数据绑定是在adapter中,adapter中有个getCount()方法就是返回viewpager显示图片的张数,那么我们要实现无限循环的话,那么getCount()方法可以返回500,但是一般都是返回int类型的最大数,也就是 Integer.MAX_VALUE,还有就是比如滑动到6个位置的时候其实是显示第一张图片,而adapter中有个instantiateItem(View arg0, int arg1)就是显示显示图片的控件对象,而且还自动滑动,这个一般都是使用handler的post…方法,具体看代码,
package com.example.autoviewpager;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnPageChangeListener {
private ViewPager viewpager;
private int[] imagesid;
private List<ImageView> list;// viewpager资源
private int num = 300;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
list = new ArrayList<ImageView>();
viewpager = (ViewPager) findViewById(R.id.viewpager);
imagesid = new int[] { R.drawable.qq, R.drawable.ee, R.drawable.rr };
for (int i = 0; i < imagesid.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imagesid[i]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
list.add(imageView);
}
viewpager.setOnPageChangeListener(this);
viewpager.setAdapter(new MyAdapter());
viewpager.setCurrentItem(num);
//延时2秒执行
mHandler.postDelayed(mRunnable, 5000);
}
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
public void run() {
// 每隔多长时间执行一次
mHandler.postDelayed(this, 1000 * 5);
num++;
viewHandler.sendEmptyMessage(num);
}
};
private final Handler viewHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
viewpager.setCurrentItem(msg.what);
super.handleMessage(msg);
}
};
class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
}
@Override
public Object instantiateItem(View arg0, int arg1) {
try {
((ViewPager) arg0).addView((View) list.get(arg1 % list.size()),0);
} catch (Exception e) {
}
return list.get(arg1 % list.size());
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
num = arg0;
arg0 = arg0%list.size();
//在这显示小点图
}
}
版权声明:本文为coderinchina原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。