一、布局设置
使用ViewPager来设置主广告,这样既可左右滑动切换
2、滑动切换的时候需要设置一个OnPageChangeListener监听器,当广告切换的时候,利用监听器设置圆点的实心和空心。
public void onPageSelected(int position) {
currentItem = position;
tv_title.setText(titles[position]);
//第几个选中的圆点实心
dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
dots.get(position).setBackgroundResource(R.drawable.dot_focused);
oldPosition = position;
}
3、设置pagerAdapter
/**
* 填充ViewPager页面的适配器
*
* @author Administrator
*
*/
private class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return imageResId.length;
}
@Override
public Object instantiateItem(View arg0, int arg1) {
System.out.println("shilihua...");
((ViewPager) arg0).addView(imageViews.get(arg1));
return imageViews.get(arg1);
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
System.out.println("destroyItem....");
((ViewPager) arg0).removeView((View) arg2);
}
@Override
//考虑成arg0 为viewPager加载的内容,arg1为instaitateItem返回的View
public boolean isViewFromObject(View arg0, Object arg1) {
boolean b=arg0 == arg1;
System.out.println("check...."+b);
return arg0 == arg1;
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
//需要刷新用这个?
return POSITION_NONE;
}
@Override
public Parcelable saveState() {
return null;
}
/*
* 每当页面发生变化的时候startUpdate... instant destory check finishUpdate..
* 参考:http://www.jishuziyuan.com/archive/Kaiewii/7821846.html
* */
@Override
public void startUpdate(View arg0) {
System.out.println("startUpdate");
}
@Override
public void finishUpdate(View arg0) {
System.out.println("finishUpdate");
}
}
}
4、自动滚动,设置一个定时器
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// 当Activity显示出来后,每两秒钟切换一次图片显示
scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2, TimeUnit.SECONDS);
/**
* 换行切换任务
*
* @author Administrator
*
*/
private class ScrollTask implements Runnable {
public void run() {
synchronized (viewPager) {
System.out.println("currentItem: " + currentItem);
currentItem = (currentItem + 1) % imageViews.size();
handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
}
}
}
// 切换当前显示的图片
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
};
};