android广告轮播无限(自定义控件)
1, 效果图
layout_slideshow.xml
布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" /> <LinearLayout android:id="@+id/dotLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:padding="8dp" android:gravity="right" android:orientation="horizontal"> //默认情况下面的点 <View android:id="@+id/v_dot1" android:layout_width="8dp" android:layout_height="8dp" android:background="@drawable/dot_focus" /> <View android:id="@+id/v_dot2" android:layout_width="8dp" android:layout_height="8dp" android:layout_marginLeft="5dp" android:background="@drawable/dot_blur" /> </LinearLayout> </RelativeLayout>
SlideShowView.java
/** * ViewPager实现的轮播图广告自定义视图,如京东首页的广告轮播图效果; * 既支持自动轮播页面也支持手势滑动切换页面 * * */ public class SlideShowView extends FrameLayout { // 使用universal-image-loader插件读取网络图片,需要工程导入universal-image-loader-1.8.6-with-sources.jar private ImageLoader imageLoader = ImageLoader.getInstance(); //轮播图图片数量 private final static int IMAGE_COUNT = 5; //自动轮播的时间间隔 private final static int TIME_INTERVAL = 5; //自动轮播启用开关 private final static boolean isAutoPlay = true; //自定义轮播图的资源 private String[] imageUrls = new String[]{ "http://image.zcool.com.cn/56/35/1303967876491.jpg", "http://image.zcool.com.cn/59/54/m_1303967870670.jpg", "http://image.zcool.com.cn/47/19/1280115949992.jpg", "http://image.zcool.com.cn/59/11/m_1303967844788.jpg"};; //放轮播图片的ImageView 的list private List<ImageView> imageViewsList; //放圆点的View的list private List<View> dotViewsList; private ViewPager viewPager; //当前轮播页 private int currentItem = 0; //定时任务 private ScheduledExecutorService scheduledExecutorService; private Context context; //Handler private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); viewPager.setCurrentItem(viewPager .getCurrentItem() + 1); } }; public SlideShowView(Context context) { this(context,null); // TODO Auto-generated constructor stub } public SlideShowView(Context context, AttributeSet attrs) { this(context, attrs, 0); // TODO Auto-generated constructor stub } public SlideShowView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.context = context; initImageLoader(context); initData(); initUI( context); if(isAutoPlay){ startPlay(); } } /** * 开始轮播图切换 */ private void startPlay(){ scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 3, TimeUnit.SECONDS); } /** * 停止轮播图切换 */ private void stopPlay(){ scheduledExecutorService.shutdown(); } /** * 初始化相关Data */ private void initData(){ //图片的集合 imageViewsList = new ArrayList<ImageView>(); //小圆点 的集合 dotViewsList = new ArrayList<View>(); } /** * 初始化Views等UI */ private void initUI(Context context){ if(imageUrls == null || imageUrls.length == 0) return; LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true); // 子布局 LinearLayout dotLayout = (LinearLayout)findViewById(R.id.dotLayout); dotLayout.removeAllViews(); // 热点个数与图片特殊相等 for (int i = 0; i < imageUrls.length; i++) { /** * 图片 */ ImageView view = new ImageView(context); view.setTag(imageUrls[i]); if(i==0){//给一个默认图 view.setBackgroundResource(R.drawable.appmain_subject_1); } view.setScaleType(ScaleType.FIT_XY); imageViewsList.add(view); /** * 小圆点 */ ImageView dotView = new ImageView(context); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); params.leftMargin = 4; params.rightMargin = 4; params.gravity=Gravity.CENTER; dotLayout.addView(dotView, params); dotViewsList.add(dotView); } viewPager = (ViewPager) findViewById(R.id.viewPager); viewPager.setFocusable(true); viewPager.setAdapter(new MyPagerAdapter()); viewPager.setOnPageChangeListener(new MyPageChangeListener()); // 设置应用打开时显示的第一项,index的值为0 // 使用这种方式得到的0,和直接写0有什么区别呢? // 直接写0,应用打开后不能直接向右滑动,因为viewpager中存image位置不能为负值,只能先向左滑动 // 这种方式得到的0,可以实现应用一打开,就可以向右滑动 int index = Integer.MAX_VALUE / 2 - 3; viewPager.setCurrentItem(index); } /** * 填充ViewPager的页面适配器 * */ private class MyPagerAdapter extends PagerAdapter{ // // @Override // public void destroyItem(View container, int position, Object object) { // // TODO Auto-generated method stub // //((ViewPag.er)container).removeView((View)object); //// ((ViewPager)container).removeView(imageViewsList.get(position)); // ((ViewPager)container).removeView(imageViewsList.get(position % imageViewsList.size())); // container.removeView(imageViewsList.get(position // % imageViewsList.size())); // } // 当某一页滑出去的时候,将其销毁 @Override public void destroyItem(ViewGroup container, int position, Object object) { // container.removeView(imageViewsList.get(position // % imageViewsList.size())); } @Override public Object instantiateItem(View container, int position) { ImageView imageView = imageViewsList.get(position % imageViewsList.size()); imageLoader.displayImage(imageView.getTag() + "", imageView); //如果View已经在之前添加到了一个父组件,则必须先remove,否则会抛出IllegalStateException。 ViewParent vp =imageView.getParent(); if (vp!=null){ ViewGroup parent = (ViewGroup)vp; parent.removeView(imageView); } ((ViewPager)container).addView(imageViewsList.get(position % imageViewsList.size())); return imageViewsList.get(position % imageViewsList.size()); } @Override public int getCount() { // return imageViewsList.size(); return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { // TODO Auto-generated method stub } @Override public Parcelable saveState() { // TODO Auto-generated method stub return null; } @Override public void startUpdate(View arg0) { // TODO Auto-generated method stub } @Override public void finishUpdate(View arg0) { // TODO Auto-generated method stub } } /** * ViewPager的监听器 * 当ViewPager中页面的状态发生改变时调用 * */ private class MyPageChangeListener implements OnPageChangeListener{ boolean isAutoPlay = false; @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub switch (arg0) { case 1:// 手势滑动,空闲中 isAutoPlay = false; break; case 2:// 界面切换中 isAutoPlay = true; break; case 0:// 滑动结束,即切换完毕或者加载完毕 // 当前为最后一张,此时从右向左滑,则切换到第一张 // if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !isAutoPlay) { // viewPager.setCurrentItem(0); // } // // 当前为第一张,此时从左向右滑,则切换到最后一张 // else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) { // viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1); // } if ( !isAutoPlay) { //滑动手指 //// //// viewPager.setCurrentItem(arg0); // currentItem++; // viewPager.setCurrentItem(viewPager.getCurrentItem()+1); } break; } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int position) { // TODO Auto-generated method stub // 当页面滑动结束时,先对页面位置取模 position = position % imageViewsList.size(); for(int i=0;i < dotViewsList.size();i++){ if(i == position){ ((View)dotViewsList.get(position)).setBackgroundResource(R.drawable.dot_focus); }else { ((View)dotViewsList.get(i)).setBackgroundResource(R.drawable.dot_blur); } } currentItem = position; } } /** *执行轮播图切换任务 * */ private class SlideShowTask implements Runnable{ @Override public void run() { // TODO Auto-generated method stub synchronized (viewPager) { handler.obtainMessage().sendToTarget(); } } } /** * 销毁ImageView资源,回收内存 * */ private void destoryBitmaps() { for (int i = 0; i < IMAGE_COUNT; i++) { ImageView imageView = imageViewsList.get(i); Drawable drawable = imageView.getDrawable(); if (drawable != null) { //解除drawable对view的引用 drawable.setCallback(null); } } } /** * ImageLoader 图片组件初始化 * * @param context */ public static void initImageLoader(Context context) { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).writeDebugLogs() // Remove // app .build(); ImageLoader.getInstance().init(config); } }
使用的时候
<!-- 主题图片 --> <com.example.slideshowdemo.customview.SlideShowView android:id="@+id/slideshowView" android:layout_width="fill_parent" android:layout_height="180dp" android:layout_centerHorizontal="true" />