Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 的 layout.xml 中載入自訂 View 類別

編輯:關於 Android 程式設計

Android 允許開發者自訂 View 元件,並直接於版面配置檔中引用。本文示範如何在 layout.xml 中使用全限定類別名稱來載入自訂的 View,並以一個會定時切換圖片的 GGView3 為例說明其內部實作。

在版面中引用自訂 View

只要在 XML 中寫入自訂 View 的完整類別路徑,Android 便會在解析版面時自動實例化它:

<com.bn.summer.GGView3
    android:layout_width="100dip"
    android:layout_height="114dip"
    android:layout_marginLeft="11dip" />

自訂 View 的實作

此 View 繼承自 View,建構子中必須接收 Context 與 AttributeSet,這是為了讓系統能從 XML 正確實例化。範例在內部啟動了一個執行緒,每隔一段時間切換要繪製的圖片並呼叫 postInvalidate 觸發重繪。

package com.bn.summer;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class GGView3 extends View {
    int COMPONENT_WIDTH;
    int COMPONENT_HEIGHT;
    boolean initflag = false;
    Bitmap[] bma;
    Paint paint;
    int[] drawablesId;
    int currIndex = 0;
    boolean workFlag = true;

    public GGView3(Context father, AttributeSet as) {
        super(father, as);
        this.drawablesId = new int[] {
            R.drawable.room1,
            R.drawable.room2,
            R.drawable.room3,
        };
        bma = new Bitmap[drawablesId.length];
        initBitmaps();
        paint = new Paint();
        paint.setFlags(Paint.ANTI_ALIAS_FLAG); // 消除鋸齒
        new Thread() {
            public void run() {
                while (workFlag) {
                    currIndex = (currIndex + 1) % drawablesId.length;
                    GGView3.this.postInvalidate();
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public void initBitmaps() {
        Resources res = this.getResources();
        for (int i = 0; i < drawablesId.length; i++) {
            bma[i] = BitmapFactory.decodeResource(res, drawablesId[i]);
        }
    }

    public void onDraw(Canvas canvas) {
        if (!initflag) {
            COMPONENT_WIDTH = this.getWidth();  // 取得 view 的寬度
            COMPONENT_HEIGHT = this.getHeight(); // 取得 view 的高度
            initflag = true;
        }
        int picWidth = bma[currIndex].getWidth();
        int picHeight = bma[currIndex].getHeight();
        int startX = (COMPONENT_WIDTH - picWidth) / 2;
        int startY = (COMPONENT_HEIGHT - picHeight) / 2;
        // 繪製背景色
        canvas.drawARGB(255, 200, 128, 128);
        canvas.drawBitmap(bma[currIndex], startX, startY, paint);
    }
}

幾個重點:自訂 View 若要在 XML 中使用,務必提供接收 AttributeSet 的建構子;在 onDraw 中首次取得元件寬高後以旗標記錄,避免重複計算;而更新畫面時應透過 postInvalidate 而非直接在子執行緒操作 UI,以確保執行緒安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved