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

Android 自訂 View 及其在佈局文件中的使用示例

編輯:關於 Android 程式設計

前言

儘管 Android 已提供 Button、ImageView、TextView、EditText 等豐富控制項,但在實際專案中,仍常需要開發者自訂可重複使用的控制項,讓它能像系統控制項一樣方便使用。所幸 Android 為自訂控制項提供了完整的基礎類別(如 View、Canvas)與 XML 標籤(如 declare-styleable、attr),讓整個過程有章可循。

建立流程

一、在 values 目錄建立名為 attrs 的 XML 檔



    
        
        
        
    

外層的 <declare-styleable name="CustomView"> 讓自訂 View 擁有自身屬性,裡面定義了 textString(顯示文字)、colorValue(字體顏色)、textSize(字體大小)三個屬性,使用起來就像設定 TextView 的 textSize、textColor 一樣直觀。

為何 declare-styleable 的 name 要與自訂 View 的類別名一致?依 Google 文件的說法,這是慣例:雖然並非強制,但許多熱門程式碼編輯器依賴這個命名慣例來提供程式碼自動補全。

二、編寫佈局文件並引用自訂 View



    

此處有兩個重點:

  1. 新增命名空間:自訂屬性不屬於 https://schemas.android.com/apk/res/android,而屬於 https://schemas.android.com/apk/res/[你的套件名稱],所以要加上 xmlns:app="https://schemas.android.com/apk/res/com.project.summary"。
  2. 引用方式:要寫完整套件名稱 <com.project.summary.customview.CustomView。若 CustomView 是 ParentCustomView 的內部類,則需寫成 <com.project.summary.customview.ParentCustomView$CustomView,中間以 $ 連接。設定自訂屬性時前面要加 app 前綴。

三、編寫自訂 View 程式碼

Google 文件要求自訂 View 至少要有一個以 Context 與 AttributeSet 為參數的建構子,原因有二:其一,讓 layout editor 能創建與編輯你的 View;其二(也是主因),當 View 從 XML 佈局創建時,標籤中的所有屬性會被讀進資源包並以 AttributeSet 傳入建構子,接著可用 obtainStyledAttributes() 把屬性轉成 TypedArray 陣列,再以預定義常量輕鬆讀取。

public class CustomView extends View {

    private int color;
    private String mText;
    private int textSize;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
        try {
            mText = a.getString(R.styleable.CustomView_textString);
            color = a.getColor(R.styleable.CustomView_colorValue, R.color.textRed);
            textSize = a.getDimensionPixelOffset(R.styleable.CustomView_textSize, 20);
        } finally {
            a.recycle(); // 記得回收 TypedArray
        }
    }
}

可以用 TypedArray 提供的相關方法取出佈局中設定的屬性,別忘了最後要回收。

四、完整示例

本例自訂了一個用來顯示文字的 View,功能類似 TextView(由於本文聚焦於自訂 View 的創建與使用,功能細節從略):

public class CustomView extends View {

    private int color;
    private Paint mTextPaint;
    private String mText;
    private int textSize;
    private int mAscent;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
        try {
            mText = a.getString(R.styleable.CustomView_textString);
            color = a.getColor(R.styleable.CustomView_colorValue, R.color.textRed);
            if (mText != null) {
                setCustomText(mText);
            }
            setTextColor(color);
            textSize = a.getDimensionPixelOffset(R.styleable.CustomView_textSize, 20);
            if (textSize > 0) {
                setTextSize(textSize);
            }
        } finally {
            a.recycle();
        }
    }

    private void setCustomText(String text) {
        mText = text;
        requestLayout();
        invalidate();
    }

    private final void initLabelView() {
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        // 手動縮放文字大小以符合螢幕密度
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);
        setPadding(3, 3, 3, 3);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
    }

    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight();
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        mAscent = (int) mTextPaint.ascent();
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop() + getPaddingBottom();
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    public void setTextSize(int size) {
        mTextPaint.setTextSize(size);
        requestLayout();
        invalidate();
    }

    public void setTextColor(int color) {
        mTextPaint.setColor(color);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
    }
}

附錄:format 的定義與應用示例

  • reference(資源引用):<attr name="background" format="reference" />
  • color(顏色值):<attr name="textColor" format="color" />
  • boolean(布爾值):<attr name="focusable" format="boolean" />
  • dimension(尺寸值):<attr name="customWidth" format="dimension" />
  • float(浮點值):<attr name="fromAlpha" format="float" />
  • integer(整型值):<attr name="frameDuration" format="integer" />
  • string(字串):<attr name="textString" format="string" />
  • fraction(百分比):<attr name="pivotX" format="fraction" />
  • enum(列舉值):
    
        
        
    
  • flag(位元或運算):可將多個 flag 以 | 組合使用。

掌握 attrs 定義、命名空間設定、以 obtainStyledAttributes 讀取屬性,以及 onMeasure/onDraw 的重寫,就能打造出具備自訂屬性、可在 XML 中靈活使用的自訂控制項。

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