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

时间: 2024-10-10 21:57:52

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

Android ViewPager实现循环轮播图

一.原理 ViewPager是Android中使用频率相对较高的view组件,同时对滑动过程中的事件进行了处理,因此非常适合轮播图.关于轮播图的实现,有很多方法,使用HorizontalView或者RecylerView也可以实现,但是需要处理fling操作,这里我们用ViewPager避免这些工作. 网上有很多关于ViewPager轮播的轮播实现,其原理大多数给PagerAdapter的getCount 放大N倍,N大于100,1000等.这里我们使用另一种思路,数据映射. 数据映射方案:假设

Android侧滑菜单和轮播图之滑动冲突

接手一个项目,有一个问题需要修改:轮播图不能手动滑动,手动滑动轮播图只会触发侧滑菜单. 猜测:viewpager控件(轮播图)的触摸事件被SlidingMenu控件(侧滑菜单,非第三方项目,乃是上个开发人员自定义的)拦截了. 基于这个猜测,我自定义一个ViewPager,重写dispatchTouchEvent.onInterceptTouchEvent和onTouchEvent,分别在这三个方法中打印log: 重写SlidingMenu的dispatchTouchEvent.onInterce

vue中使用轮播图插件carousel,克隆的图片点击事件无效的解决办法

1 <div class="students-box" @click="clickSwiper"> 2 // 将点击事件绑定在父元素上 3 <carousel 4 :items="5" 5 :autoplay="true" 6 :nav="true" 7 :margin="20" 8 :loop="true" 9 :autoplayTimeout=&

Android开发之ViewPager实现轮播图(轮播广告)效果的自定义View

最近开发中需要做一个类似京东首页那样的广告轮播效果,于是采用ViewPager自己自定义了一个轮播图效果的View. 主要原理就是利用定时任务器定时切换ViewPager的页面. 效果图如下: 主页面布局实现如下: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android&

Android自定义控件5--轮播图广告ViewPager基本实现

本文地址:http://www.cnblogs.com/wuyudong/p/5918021.html,转载请注明源地址. 本文开始实现轮播图广告系列,这篇文章首先实现让图片滑动起来(ViewPager),效果如下: 首先实现布局 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools&

Android自定义控件6--轮播图广告的实现

本文接着实现轮播图广告的监听滚动 本文地址:http://www.cnblogs.com/wuyudong/p/5920757.html,转载请注明源地址. 首先添加布局文件,实现小白点 shape_bg_point_enable.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/andro

Android轮播图封装,下拉刷新相结合

自定义轮播图CarouselView 自定义下拉刷新PullRefreshListView 马上就要正式做毕业设计了,一些零碎时间写其中的一个模块,现记录下来,以备以后忘记时使用.欢迎大神不吝纠正. 效果图: layout_carousel.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com

手把手原生js简单轮播图

在团队带人,突然被人问到轮播图如何实现,进入前端领域有一年多了,但很久没自己写过,一直是用大牛写的插件,今天就写个简单的适合入门者学习的小教程.当然,轮播图的实现原理与设计模式有很多种,我这里讲的是用面向过程函数式编程去实现,相对于面向对象设计模式,代码难免会显得臃肿冗余.但没有面向对象的抽象却很适合新手理解与学习.已经在BAT的同学看到希望少喷点.另外可以多提意见. 轮播图的原理: 一系列的大小相等的图片平铺,利用CSS布局只显示一张图片,其余隐藏.通过计算偏移量利用定时器实现自动播放,或通过

jq轮播图插件

/* * 使用说明  *    *   1:需要提供一个标签   *   2:lis:图片的个数 *   3:轮播图的大小 width ,height *   4:图片的地址imgs[0].carouselImg[0] 这是本人的地址, $('#mainCarousel').jdCarousel({lis:7,width:800,height:340,          imgSrc:[                 imgs[0].carouselImg[0],