歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android簡單的廣告控件View

Android簡單的廣告控件View

日期:2017/3/1 10:27:17   编辑:Linux編程

在布局文件中引用此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. public GGView(Context father, AttributeSet as) { // 構造器
  11. super(father, as);
  12. drawablesId = new int[] { // 初始化圖片ID數組
  13. R.drawable.adv1, // 將需要播放的圖片ID放於此處即可
  14. R.drawable.adv2, R.drawable.adv3, };
  15. bma = new Bitmap[drawablesId.length]; // 創建存放圖片的數組
  16. initBitmaps(); // 調用初始化圖片函數,初始化圖片數組
  17. paint = new Paint(); // 創建畫筆
  18. paint.setFlags(Paint.ANTI_ALIAS_FLAG); // 消除鋸齒
  19. new Thread() { // 創建播放圖片線程
  20. public void run() {
  21. while (workFlag) {
  22. currIndex = (currIndex + 1) % drawablesId.length;// 改變ID數組下標值
  23. GGView.this.postInvalidate(); // 繪制
  24. try {
  25. Thread.sleep(3000); // 休息三秒
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. }.start(); // 啟動線程
  32. }
  33. public void initBitmaps() { // 初始化圖片函數
  34. Resources res = this.getResources(); // 獲取Resources對象
  35. for (int i = 0; i < drawablesId.length; i++) {
  36. bma[i] = BitmapFactory.decodeResource(res, drawablesId[i]);
  37. }
  38. }
  39. public void onDraw(Canvas canvas) { // 繪制函數
  40. if (!initflag) { // 第一次繪制時需要獲取寬度和高度
  41. COMPONENT_WIDTH = this.getWidth(); // 獲取view的寬度
  42. COMPONENT_HEIGHT = this.getHeight(); // 獲取view的高度
  43. initflag = true;
  44. }
  45. int picWidth = bma[currIndex].getWidth(); // 獲取當前繪制圖片的寬度
  46. int picHeight = bma[currIndex].getHeight(); // 獲取當前繪制圖片的高度
  47. int startX = (COMPONENT_WIDTH - picWidth) / 2; // 得到繪制圖片的左上角X坐標
  48. int startY = (COMPONENT_HEIGHT - picHeight) / 2; // 得到繪制圖片的左上角Y坐標
  49. canvas.drawARGB(255, 200, 128, 128); // 設置背景色
  50. canvas.drawBitmap(bma[currIndex], startX, startY, paint); // 繪制圖片
  51. }
  52. }
Copyright © Linux教程網 All Rights Reserved