android ViewPager实现的轮播图广告自定义视图,网络获取图片和数据

public class SlideShowAdView extends FrameLayout {

    //轮播图图片数量
    private static int IMAGE_COUNT = 3;
    //自动轮播的时间间隔
    private final static int TIME_INTERVAL = 5;
    //自动轮播启用开关
    private final static boolean isAutoPlay = false;
   
    //自定义轮播图的资源ID
    private List imageAd;
    //放轮播图片的ImageView 的list
    private List imageViewsList;
    //放圆点的View的list
    private List dotViewsList;
   
    private ViewPager viewPager;
   
    private DisplayImageOptions options;
   
    private Context context;
    //当前轮播页
    private int currentItem  = 0;
    //定时任务
    private ScheduledExecutorService scheduledExecutorService;
    //Handler
    private Handler handler = new Handler(){

     
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentItem);
        }
       
    };
   
    private void initNeedUtil()
    {
     options = new DisplayImageOptions.Builder()
  .showStubImage(R.drawable.jky_jzsbd)
  // 设置图片下载期间显示的图片
  .showImageForEmptyUri(R.drawable.jky_jzsbd)
  // 设置图片Uri为空或是错误的时候显示的图片
  .showImageOnFail(R.drawable.jky_jzsbd)
  // 设置图片加载或解码过程中发生错误显示的图片
  .cacheInMemory(true)
  // 设置下载的图片是否缓存在内存中
  .cacheOnDisc(true)
  // 设置下载的图片是否缓存在SD卡中
  .imageScaleType(ImageScaleType.NONE)
  .bitmapConfig(Bitmap.Config.RGB_565)// 防止内存溢出的,图片太多就这这个。还有其他设置
  // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
  .build();

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
  context).threadPriority(Thread.NORM_PRIORITY - 2)
  .denyCacheImageMultipleSizesInMemory()
  .discCacheFileNameGenerator(new Md5FileNameGenerator())
  .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
  .memoryCacheSize(2 * 1024 * 1024)// 缓存大小
  .discCacheSize(50 * 1024 * 1024)// 存储卡缓存大小
  .discCacheFileCount(100)// 文件数量
  .tasksProcessingOrder(QueueProcessingType.LIFO).build();
ImageLoader.getInstance().init(config);// 创建配置过得DisplayImageOption对象

    }
   
    public SlideShowAdView(Context context) {
        this(context,null);
        // TODO Auto-generated constructor stub
        this.context=context;
        initNeedUtil();
    }
    public SlideShowAdView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        // TODO Auto-generated constructor stub
        this.context=context;
        initNeedUtil();
    }
    public SlideShowAdView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        this.context=context;
        initNeedUtil();
        initData(context);
    }
   
    private void startPlay(){
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }
   
    private void stopPlay(){
        scheduledExecutorService.shutdown();
    }
   
    private void initData(Context context){
        imageViewsList = new ArrayList();
        dotViewsList = new ArrayList();
       
        try {
         // 开一条子线程加载网络数据
         Runnable runnable = new Runnable() {
          public void run() {
           try {
            imageAd=new ProductUtils().GetIndexAdInfo();
            // 发送消息,并把jsonArray结合对象传递过去
            handler.sendMessage(handler.obtainMessage(0));
           } catch (Exception e) {
            e.printStackTrace();
           }
          }
         };
         // 开启线程
         new Thread(runnable).start();
         // handler与线程之间的通信及数据处理
         handler = new Handler() {
          public void handleMessage(Message msg) {
           if (msg.what == 0) {
            initUI();
           }
          }
         };
        } catch (Exception e) {

        }
    }
   
    private void initUI(){
        LayoutInflater.from(context).inflate(R.layout.layout_slideadshow, this, true);
        for(int i=0;i
            ImageView view =  new ImageView(context);
            view.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(
        imageAd.get(i).imgUrl,
        view, options);
            view.setTag(imageAd.get(i).ClassId);
            final String className=imageAd.get(i).className;
            final int classId=imageAd.get(i).ClassId;
            final String imgU=imageAd.get(i).imgUrl;
            final int cStep=i;
            view.setOnClickListener(new OnClickListener(){
           
    @Override
    public void onClick(View arg0) {
          Intent intent=new Intent(context,PromotionActivity.class);
     intent.putExtra("actid", classId);
     intent.putExtra("ctitle", className);
     intent.putExtra("cUrl", imgU);
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 context.startActivity(intent);
    
    }});
            imageViewsList.add(view);
        }
        dotViewsList.add(findViewById(R.id.v_dot1));
        dotViewsList.add(findViewById(R.id.v_dot2));
        dotViewsList.add(findViewById(R.id.v_dot3));
       
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setFocusable(true);
       
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());

        if(isAutoPlay){
            startPlay();
        }
    }
   
   
    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));
        }

        @Override
        public Object instantiateItem(View container, int position) {
            // TODO Auto-generated method stub
            ((ViewPager)container).addView(imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imageViewsList.size();
        }

        @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
           
        }
       
    }
   
    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);
                }
                break;
        }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
           
        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
           
            currentItem = pos;
            for(int i=0;i < dotViewsList.size();i++){
                if(i == pos){
                    ((View)dotViewsList.get(pos)).setBackgroundResource(R.drawable.dot_black);
                }else {
                    ((View)dotViewsList.get(i)).setBackgroundResource(R.drawable.dot_white);
                }
            }
        }
       
    }
   
   
    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (viewPager) {
                currentItem = (currentItem+1)%imageViewsList.size();
                handler.obtainMessage().sendToTarget();
            }
        }
       
    }
   
    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);
            }
        }
    }
   
}

posted @ 2015-09-03 14:40  java高级技术汇  阅读(673)  评论(0编辑  收藏  举报