java制作广告图片自动轮播控件

首页图片的轮播

/**
 * 广告图片自动轮播控件</br>
 *
 */
public class ImageCycleView extends LinearLayout {
  /**
   * 上下文
   */
  private Context mContext;
  /**
   * 图片轮播视图
   */
  private ViewPager mAdvPager = null;
  /**
   * 滚动图片视图适配
   */
  private ImageCycleAdapter mAdvAdapter;
  /**
   * 图片轮播指示器控件
   */
  private ViewGroup mGroup;

  /**
   * 图片轮播指示个图
   */
  private ImageView mImageView = null;

  /**
   * 滚动图片指示视图列表
   */
  private ImageView[] mImageViews = null;

  /**
   * 图片滚动当前图片下标
   */

  private boolean isStop;

  /**
   * 游标是圆形还是长条,要是设置为0是长条,要是1就是圆形 默认是圆形
   */
  public int stype=1;

  /**
   * @param context
   */
  public ImageCycleView(Context context) {
    super(context);
  }

  /**
   * @param context
   * @param attrs
   */
  @SuppressLint("Recycle")
  public ImageCycleView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    LayoutInflater.from(context).inflate(R.layout.ad_cycle_view, this);
    mAdvPager = (ViewPager) findViewById(R.id.adv_pager);
    mAdvPager.setOnPageChangeListener(new GuidePageChangeListener());
    // 滚动图片右下指示器视
    mGroup = (ViewGroup) findViewById(R.id.viewGroup);
  }

  /**
   * 触摸停止计时器,抬起启动计时器
   */
  @Override
  public boolean dispatchTouchEvent(MotionEvent event) {
    if(event.getAction()==MotionEvent.ACTION_UP){
      // 开始图片滚动
      startImageTimerTask();
    }else{
      // 停止图片滚动
      stopImageTimerTask();
    }
    return super.dispatchTouchEvent(event);
  }
  /**
   * 装填图片数据
   *
   * @param imageUrlList
   * @param imageCycleViewListener
   */
  public void setImageResources(ArrayList<Integer> imageUrlList ,ImageCycleViewListener imageCycleViewListener,int stype){
    this.stype=stype;
    // 清除
    mGroup.removeAllViews();
    // 图片广告数量
    final int imageCount = imageUrlList.size();
    mImageViews = new ImageView[imageCount];
    for (int i = 0; i < imageCount; i++) {
      mImageView = new ImageView(mContext);
      LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      params.leftMargin=30;
      mImageView.setScaleType(ScaleType.CENTER_CROP);
      mImageView.setLayoutParams(params);

      mImageViews[i] = mImageView;
      if (i == 0) {
        if(this.stype==1)
//         mImageViews[i].setBackgroundResource(R.drawable.banner_dian_focus);
          mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_focus);//换点
        else
          mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_focus);
      } else {
        if(this.stype==1)
        // mImageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
        mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_blur);
        else
          mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_blur);
      }
      mGroup.addView(mImageViews[i]);
    }

    mAdvAdapter = new ImageCycleAdapter(mContext, imageUrlList ,imageCycleViewListener);
    mAdvPager.setAdapter(mAdvAdapter);
    mAdvPager.setCurrentItem(Integer.MAX_VALUE/2);
    startImageTimerTask();
  }

  public void setImageResources2(ArrayList<Integer> imageUrlList ,ImageCycleViewListener imageCycleViewListener,int stype){
    this.stype=stype;
    // 清除
    mGroup.removeAllViews();
    // 图片广告数量
    final int imageCount = imageUrlList.size();
    mImageViews = new ImageView[imageCount];
    for (int i = 0; i < imageCount; i++) {
      mImageView = new ImageView(mContext);
      LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      params.leftMargin=30;
      mImageView.setScaleType(ScaleType.CENTER_CROP);
      mImageView.setLayoutParams(params);

      mImageViews[i] = mImageView;
      if (i == 0) {
        if(this.stype==1)
//         mImageViews[i].setBackgroundResource(R.drawable.banner_dian_focus);
          mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_focus);//换点
        else
          mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_focus);
      } else {
        if(this.stype==1)
        // mImageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
        mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_blur);
        else
          mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_blur);
      }
      mGroup.addView(mImageViews[i]);
    }

    mAdvAdapter = new ImageCycleAdapter(mContext, imageUrlList ,imageCycleViewListener);
    mAdvPager.setAdapter(mAdvAdapter);
    mAdvPager.setCurrentItem(Integer.MAX_VALUE/2);
    startImageTimerTask();
  }

  /**
   * 图片轮播(手动控制自动轮播与否,便于资源控件)
   */
  public void startImageCycle() {
    startImageTimerTask();
  }

  /**
   * 暂停轮播—用于节省资源
   */
  public void pushImageCycle() {
    stopImageTimerTask();
  }

  /**
   * 图片滚动任务
   */
  private void startImageTimerTask() {
    stopImageTimerTask();
    // 图片滚动
    mHandler.postDelayed(mImageTimerTask, 5000);
  }

  /**
   * 停止图片滚动任务
   */
  private void stopImageTimerTask() {
    isStop=true;
    mHandler.removeCallbacks(mImageTimerTask);
  }

  private Handler mHandler = new Handler();

  /**
   * 图片自动轮播Task
   */
  private Runnable mImageTimerTask = new Runnable() {
    @Override
    public void run() {
      if (mImageViews != null) {
        mAdvPager.setCurrentItem(mAdvPager.getCurrentItem()+1);
        if(!isStop){ //if isStop=true  //当你退出后 要把这个给停下来 不然 这个一直存在 就一直在后台循环
          mHandler.postDelayed(mImageTimerTask, 5000);
        }

      }
    }
  };

  /**
   * 轮播图片监听
   *
   * @author minking
   */
  private final class GuidePageChangeListener implements OnPageChangeListener {
    @Override
    public void onPageScrollStateChanged(int state) {
      if (state == ViewPager.SCROLL_STATE_IDLE)
        startImageTimerTask();
    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }
    @Override
    public void onPageSelected(int index) {
      index=index%mImageViews.length;
      // 设置当前显示的图片
      // 设置图片滚动指示器背
      if(stype!=1)
        mImageViews[index].setBackgroundResource(R.drawable.cicle_banner_dian_focus);
      else
        mImageViews[index].setBackgroundResource(R.drawable.cicle_banner_dian_focus);
      for (int i = 0; i < mImageViews.length; i++) {
        if (index != i) {
          if(stype!=1)
            mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_blur);
          else
            mImageViews[i].setBackgroundResource(R.drawable.cicle_banner_dian_blur);
        }
      }
    }
  }

  private class ImageCycleAdapter extends PagerAdapter {

    /**
     * 图片视图缓存列表
     */
    private ArrayList<SmartImageView> mImageViewCacheList;

    /**
     * 图片资源列表
     */
    //private ArrayList<String> mAdList = new ArrayList<String>();
    private ArrayList<Integer> mAdList = new ArrayList<Integer>();

    /**
     * 广告图片点击监听
     */
    private ImageCycleViewListener mImageCycleViewListener;

    private Context mContext;
//   public ImageCycleAdapter(Context context, ArrayList<String> adList , ImageCycleViewListener imageCycleViewListener) {
//     this.mContext = context;
//     this.mAdList = adList;
//     mImageCycleViewListener = imageCycleViewListener;
//     mImageViewCacheList = new ArrayList<SmartImageView>();
//   }
    public ImageCycleAdapter(Context context, ArrayList<Integer> adList , ImageCycleViewListener imageCycleViewListener) {
      this.mContext = context;
      this.mAdList = adList;
      mImageCycleViewListener = imageCycleViewListener;
      mImageViewCacheList = new ArrayList<SmartImageView>();
    }

    @Override
    public int getCount() {
      return Integer.MAX_VALUE;
    }
    @Override
    public boolean isViewFromObject(View view, Object obj) {
      return view == obj;
    }
     @Override
    public Object instantiateItem(ViewGroup container, final int position) {
      int imageUrl = mAdList.get(position%mAdList.size());
      Log.e("imageUrl:",position%mAdList.size()+"--"+imageUrl+"");
      SmartImageView imageView = null;
      if (mImageViewCacheList.isEmpty()) {
        imageView = new SmartImageView(mContext);
        imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        //test
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

      }
      else {
        imageView = mImageViewCacheList.remove(0);
      }
      imageView.setTag(imageUrl);
      container.addView(imageView);
      //imageView.setImageUrl(imageUrl);
      imageView.setBackgroundResource(imageUrl);
      // 设置图片点击监听
      imageView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          mImageCycleViewListener.onImageClick(position%mAdList.size(), v);
        }
      });
      return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
      SmartImageView view = (SmartImageView) object;
      mAdvPager.removeView(view);
      mImageViewCacheList.add(view);

    }

  }

  /**
   * 轮播控件的监听事件
   *
   * @author minking
   */
  public static interface ImageCycleViewListener {

    /**
     * 单击图片事件
     *
     * @param position
     * @param imageView
     */
    public void onImageClick(int position, View imageView);
  }

}

我们再来看个基于安卓ViewPager的图片轮播控件

package me.lanfog.myandroid.widget;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class PageFlipper extends ViewPager {

  private String TAG = PageFlipper.class.getSimpleName();

  private List<View> views;
  private PagerAdapter adapter = new PagerAdapter() {

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

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }

    @Override
    public int getItemPosition(Object object) {
      return views.indexOf(object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
      container.removeView((View)object);
    }

    @Override
    public int getCount() {
      return views == null ? 0 : views.size();
    }
  };
  private OnPageChangeListener listener = new OnPageChangeListener() {

    /**
     * 将控件位置转化为数据集中的位置
     */
    public int convert(int position){
      return position == 0 ? views.size()-1 : ( position > views.size() ? 0 : position-1 );
    }

    @Override
    public void onPageSelected(int position) {
      if(listener2 != null){
        listener2.onPageSelected(convert(position));
      }
    }

    @Override
    public void onPageScrolled(int position, float percent, int offset) {
      if(listener2 != null){
        listener2.onPageScrolled(convert(position), percent, offset);
      }

      if(percent == 0){
        if(position == 0) // 切换到倒数第二页
          setCurrentItem(( views.size() - 2 ) % views.size(), false);
        else if(position == views.size() - 1) // 切换到正数第二页
          setCurrentItem(1, false);
      }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
      if(listener2 != null){
        listener2.onPageScrollStateChanged(state);
      }

      switch (state) {
      case SCROLL_STATE_IDLE: // 闲置

        if(!handler.hasMessages(START_FLIPPING))
          handler.sendEmptyMessageDelayed(START_FLIPPING, 3000); // 延时滚动

        break;
      case SCROLL_STATE_DRAGGING: // 拖动中

        handler.sendEmptyMessage(STOP_FLIPPING); // 取消滚动

        break;
      case SCROLL_STATE_SETTLING: // 拖动结束
        break;
      }
    }
  }, listener2;

  private final int START_FLIPPING = 0;
  private final int STOP_FLIPPING = 1; 

  private Handler handler = new Handler(){

    public void handleMessage(Message msg) {

      switch (msg.what) {
      case START_FLIPPING:

        if(views.size() > 3) // 因为前后页是辅助页,所以此处3也就是只有1页
          setCurrentItem((getCurrentItem() + 1) % views.size());

        handler.sendEmptyMessageDelayed(START_FLIPPING, 3000); // 延时滚动

        break;
      case STOP_FLIPPING:

        handler.removeMessages(START_FLIPPING);

        break;
      }
    }
  };

  public PageFlipper(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  public PageFlipper(Context context) {
    super(context);
    init();
  }

  private void init(){

    setOffscreenPageLimit(1); // 最大页面缓存数量
    setAdapter(adapter); // 适配器
    super.setOnPageChangeListener(listener); // 监听器

    handler.sendEmptyMessageDelayed(START_FLIPPING, 3000); // 延时滚动
  }

  public void setViews(int[] ids){
    this.views = new ArrayList<View>();
    for(int i=0;i<ids.length+2;i++){ // 头部新增一个尾页,尾部新增一个首页

      ImageView iv = new ImageView(getContext());
      iv.setImageResource(ids[i == 0 ? ids.length-1 : ( i > ids.length ? 0 : i-1 )]);
      iv.setScaleType(ImageView.ScaleType.FIT_XY);
      this.views.add(iv);
    }
    setCurrentItem(1); // 首页
    this.adapter.notifyDataSetChanged();
  }

  @Override
  public void setOnPageChangeListener(OnPageChangeListener listener) {
    this.listener2 = listener;
  }

}
(0)

相关推荐

  • java截取网页图片的方法

    本文实例讲述了java截取网页图片的方法.分享给大家供大家参考.具体如下: 这是调用第三方控件,然后在读取图片文件存入数据库 public static int GetPic(String URL,String ADid){ String path=CatPath+"iecapt.exe"; Process pro = null; try { pro = Runtime.getRuntime().exec(path + " " + URL + " &quo

  • java实现图片裁切的工具类实例

    本文实例讲述了java实现图片裁切的工具类.分享给大家供大家参考,具体如下: package com.yanek.util; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import javax.im

  • JAVA比较两张图片相似度的方法

    本文实例讲述了JAVA比较两张图片相似度的方法.分享给大家供大家参考.具体如下: 摘要: importjava.awt.image.BufferedImage; importjava.io.File; importjavax.imageio.ImageIO; /***比较两张图片的相似度*@authorGuihua**/publicclassBMPLoader{//改变成二进制码 publicstaticString[][]getPX(Stringargs){int[]rgb=newint[3]

  • java实现图片写入高清字体及带边框的方法

    本文实例讲述了java实现图片写入高清字体及带边框的方法.分享给大家供大家参考.具体实现方法如下: Graphics2D g2=image.createGraphics(); //g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingH

  • Java图片处理 (文字水印、图片水印、缩放、补白)代码实例

    package com.hmw.picMark; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.im

  • java通过模拟post方式提交表单实现图片上传功能实例

    本文实例讲述了java通过模拟post方式提交表单实现图片上传功能.分享给大家供大家参考,具体如下: 模拟表单html如下: <form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1"> <label> <input type="tex

  • Java如何实现图片裁剪预览功能

    在项目中,我们需要做些类似头像上传,图片裁剪的功能,ok看下面文章! 需要插件:jQuery Jcrop 后端代码: package org.csg.upload; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Itera

  • 使用Java代码在Android中实现图片裁剪功能

    前言 Android应用中经常会遇到上传相册图片的需求,这里记录一下如何进行相册图片的选取和裁剪. 相册选取图片 1. 激活相册或是文件管理器,来获取相片,代码如下: private static final int TAKE_PICTURE_FROM_ALBUM = 1; private void takePictureFromAlbum() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("ima

  • Java实现给网站上传图片盖章的方法

    本文实例讲述了Java实现给网站上传图片盖章的方法.分享给大家供大家参考.具体如下: 最近无聊,上了一会校友录,觉的校友录的图片都会加入一个章,呵呵,自己也就做了一个,不过只适合jpg格式.发出来给大家研究研究.欢迎讨论! 很老的代码了 /************************************************ * <p>java对图片的操作(只能使用jpg)</p> * 对图片的签章<br> * 对图片的缩图<br> * <p

  • java编程简单获取图片像素的方法

    本文实例讲述了java获取图片像素的方法.分享给大家供大家参考,具体如下: package cn.net.comsys.sso; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.*; public class Test { public static void main(String args[]) { File file = new File("a.bmp"); Buf

  • Java读取图片EXIF信息的方法

    本文实例讲述了Java读取图片EXIF信息的方法.分享给大家供大家参考.具体分析如下: 首先介绍一下什么是EXIF,EXIF是Exchangeable Image File的缩写,这是一种专门为数码相机照片设定的格式.这种格式可以用来记录数字照片的属性信息,例如相机的品牌及型号.相片的拍摄时间.拍摄时所设置 的光圈大小.快门速度.ISO等等信息.除此之外它还能够记录拍摄数据,以及照片格式化方式,这样就可以输出到兼容EXIF格式的外设上,例如照片打印机 等. 目前最常见的支持EXIF信息的图片格式

随机推荐