轮播

//-------------onCreate中------------------------
//找到控件
view_pager = (ViewPager) findViewById(R.id.view_pager);
//设置适配器
adapter = new BannerAdapter(views);
view_pager.setAdapter(adapter);
//初始化view
initView();
//轮播
lunbo();
//设置默认页
view_pager.setCurrentItem(0);


//---------------轮播------------------------
//轮播
private void lunbo() {
//使用Timer发送延迟消息
Timer timer=new Timer();
TimerTask task=new TimerTask() {
int count=0;
@Override
public void run() {
int a=count++;
handler.sendEmptyMessage(a);
}
};
timer.schedule(task,1000,1000);
}
//---------------初始化view----------------------
//初始化view
private void initView() {
View view1=View.inflate(this,R.layout.item_pager1,null);
View view2=View.inflate(this,R.layout.item_pager2,null);
View view3=View.inflate(this,R.layout.item_pager3,null);
View view4=View.inflate(this,R.layout.item_pager4,null);
views.add(view1);
views.add(view2);
views.add(view3);
views.add(view4);

}

//--------------Handler---------------------
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
view_pager.setCurrentItem(msg.what);

}
};
//===============创建一个类继承pageradapter====并实现以下方法================
public class BannerAdapter extends PagerAdapter{
private List<View> views;
public BannerAdapter(List<View> views) {
this.views = views;
}

@Override
public int getCount() {
return Integer.MAX_VALUE;
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
View view=views.get(position%views.size());
container.addView(view);
return view;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
 
 
posted on 2016-08-03 12:36  巫山老妖  阅读(227)  评论(0编辑  收藏  举报