Android简单的广告控件View


在布局文件中引用此View控件即可。

  1. public class GGView extends View {  
  2.     int COMPONENT_WIDTH; // 该控件宽度   
  3.     int COMPONENT_HEIGHT; // 该控件高度   
  4.     boolean initflag = false// 是否要获取控件的高度和宽度标志   
  5.     static Bitmap[] bma; // 需要播放的图片的数组   
  6.     Paint paint; // 画笔   
  7.     int[] drawablesId; // 图片ID数组   
  8.     int currIndex = 0// 图片ID数组下标,根据此变量画图片   
  9.     boolean workFlag = true// 播放图片线程标志位   
  10.   
  11.     public GGView(Context father, AttributeSet as) { // 构造器   
  12.         super(father, as);  
  13.         drawablesId = new int[] { // 初始化图片ID数组   
  14.         R.drawable.adv1, // 将需要播放的图片ID放于此处即可   
  15.                 R.drawable.adv2, R.drawable.adv3, };  
  16.         bma = new Bitmap[drawablesId.length]; // 创建存放图片的数组   
  17.         initBitmaps(); // 调用初始化图片函数,初始化图片数组   
  18.         paint = new Paint(); // 创建画笔   
  19.         paint.setFlags(Paint.ANTI_ALIAS_FLAG); // 消除锯齿   
  20.         new Thread() { // 创建播放图片线程   
  21.             public void run() {  
  22.                 while (workFlag) {  
  23.                     currIndex = (currIndex + 1) % drawablesId.length;// 改变ID数组下标值   
  24.                     GGView.this.postInvalidate(); // 绘制   
  25.                     try {  
  26.                         Thread.sleep(3000); // 休息三秒   
  27.                     } catch (InterruptedException e) {  
  28.                         e.printStackTrace();  
  29.                     }  
  30.                 }  
  31.             }  
  32.         }.start(); // 启动线程   
  33.     }  
  34.   
  35.     public void initBitmaps() { // 初始化图片函数   
  36.         Resources res = this.getResources(); // 获取Resources对象   
  37.         for (int i = 0; i < drawablesId.length; i++) {  
  38.             bma[i] = BitmapFactory.decodeResource(res, drawablesId[i]);  
  39.         }  
  40.     }  
  41.   
  42.     public void onDraw(Canvas canvas) { // 绘制函数   
  43.         if (!initflag) { // 第一次绘制时需要获取宽度和高度   
  44.             COMPONENT_WIDTH = this.getWidth(); // 获取view的宽度   
  45.             COMPONENT_HEIGHT = this.getHeight(); // 获取view的高度   
  46.             initflag = true;  
  47.         }  
  48.         int picWidth = bma[currIndex].getWidth(); // 获取当前绘制图片的宽度   
  49.         int picHeight = bma[currIndex].getHeight(); // 获取当前绘制图片的高度   
  50.         int startX = (COMPONENT_WIDTH - picWidth) / 2// 得到绘制图片的左上角X坐标   
  51.         int startY = (COMPONENT_HEIGHT - picHeight) / 2// 得到绘制图片的左上角Y坐标   
  52.         canvas.drawARGB(255200128128); // 设置背景色   
  53.         canvas.drawBitmap(bma[currIndex], startX, startY, paint); // 绘制图片   
  54.     }  
  55. }  

相关内容