public class MainActivity extends Activity {
private ViewPager vp;
private LinearLayout line;
private List<ImageView> list;
int current=0;
int oldshow=0;
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
int i=msg.what;
if(i==1)
{
vp.setCurrentItem(current);
//设置之前的原点为未选中的状态
dots.get(oldshow).setBackgroundResource(R.drawable.dot_nolmal);
//设置当前的页面的原点为选中的状态
dots.get(current%image_url.length).setBackgroundResource(R.drawable.dot_focuse);
oldshow=current%image_url.length;
}
};
};
//网络数据
private String[] image_url = new String[] {
"http://pic8.nipic.com/20100701/5290458_114840036316_2.jpg",
"http://img3.3lian.com/2013/s1/20/d/57.jpg",
"http://pic39.nipic.com/20140226/18071023_164300608000_2.jpg",
"http://a0.att.hudong.com/15/08/300218769736132194086202411_950.jpg" };
private List<View> dots;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 寻找控件
findView();
// 为找到的控件设置数据
setData();
// 为vp设置适配器
setVpAdap();
//设置默认页面(将第一个页面只放在所有页面的中间,保证页面可以左右划 ·)
int currentitem=Integer.MAX_VALUE/2-Integer.MAX_VALUE/2%image_url.length;
vp.setCurrentItem(currentitem);
//实现自动轮播
autoPlay();
//获取原点的个数
getDotCount();
//设置第一个原点选中
dots.get(0).setBackgroundResource(R.drawable.dot_focuse);
}
private void getDotCount() {
dots = new ArrayList<View>();
//收集原点
for(int i=0;i<image_url.length;i++)
{
//获取原点所在的布局
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dot_layout, null);
//找到该布局文件下的控件
View dot=view.findViewById(R.id.dot);
//将集合存放起来动dot控件
dots.add(dot);
//将view添加到线性布局中
line.addView(view);
}
}
private void autoPlay() {
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
current=vp.getCurrentItem()+1;
handler.sendEmptyMessage(1);
}
},2000, 2000);
}
private void setVpAdap() {
vp.setAdapter(new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
@Override
public void destroyItem(ViewGroup container, int position,
Object object) {
// 销毁数据
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
//实现4张图片不断替换轮播
int item=position%image_url.length;
container.addView(list.get(item));
return list.get(item);
}
});
}
private void setData() {
list = new ArrayList<ImageView>();
BitmapUtils bit = new BitmapUtils(MainActivity.this);
for (int i = 0; i < image_url.length; i++) {
// 创建imageview控件(必须写在循环中以保证不会出现父控件错误的提示)
ImageView img = new ImageView(MainActivity.this);
// 为img控件赋值
bit.display(img, image_url[i]);
// 将赋值后的imageview控件添加到集合中
list.add(img);
}
}
private void findView() {
// 找到该布局文件下的控件
vp = (ViewPager) findViewById(R.id.vp);
line = (LinearLayout) findViewById(R.id.line);
}
}