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

動手做自訂 View:Android 自定義屬性完整實作

編輯:關於 Android 程式設計

只用系統現成的控制項,很難做出產品要的細節。想讓一個 View 能從版面檔直接指定文字、字級與顏色,就得學會「繼承 View + 自定義屬性」這套組合拳。本文用一個會把文字畫在正中央的小元件當例子,把流程走一遍。

第一步:宣告屬性(attrs.xml)

在 res/values 下新增 attrs.xml,用 declare-styleable 把屬性打包:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomViewStyle">
        <attr name="customText" format="string" />
        <attr name="customTextColor" format="color" />
        <attr name="customTextSize" format="dimension" />
    </declare-styleable>
</resources>

第二步:在版面檔中使用

使用自訂屬性前,必須先在根節點宣告命名空間。常見有兩種寫法:

xmlns:xr="https://schemas.android.com/apk/res/com.rong.test"

或者:

xmlns:xr="https://schemas.android.com/apk/res-auto"

建議用第二種。 res-auto 會自動對應目前 App 的 package,日後換包名不必回頭改版面檔。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:xr="https://schemas.android.com/apk/res/com.rong.test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:orientation="vertical" >

    <com.rong.activity.CustomView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true"
        android:background="#ff0000"
        xr:customText="自定義控件"
        xr:customTextColor="#000000"
        xr:customTextSize="40sp" />
</RelativeLayout>

第三步:繼承 View 並讀取屬性

關鍵在於建構子裡透過 obtainStyledAttributes 取得 TypedArray,用完記得 recycle():

package com.rong.activity;

import com.rong.test.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

/**
 * 自定義控件
 */
public class CustomView extends View {
    /** 自定義畫筆 */
    private Paint mPaint;
    /** 文字範圍 */
    private Rect mBounds;
    /** 自定義文字 */
    private String customText;
    /** 自定義大小 */
    private int customTextSize;
    /** 自定義顏色 */
    private int customTextColor;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomViewStyle);
        // 獲取自定義文字
        customText = typedArray.getString(R.styleable.CustomViewStyle_customText);
        // 獲取自定義文字大小
        customTextSize = typedArray.getDimensionPixelSize(R.styleable.CustomViewStyle_customTextSize, 28);
        // 獲取自定義文字顏色
        customTextColor = typedArray.getColor(R.styleable.CustomViewStyle_customTextColor, Color.WHITE);
        // 要回收這個 typedArray 對象
        typedArray.recycle();
        initView();
    }

    public void initView() {
        // 初始化畫筆
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(customTextColor);
        mPaint.setTextSize(customTextSize);
        // 生成文字區域
        mBounds = new Rect();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 獲取文字顯示區域
        mPaint.getTextBounds(customText, 0, customText.length(), mBounds);
        // 使文字水平居中:控件寬度/2 - 文字寬度/2
        float helfWidth = getWidth() / 2 - mBounds.width() / 2;
        // 使文字垂直居中
        float helfHeight = getHeight() / 2 + mBounds.height() / 2;
        // 繪制文字
        canvas.drawText(customText, helfWidth, helfHeight, mPaint);
    }
}

執行看看,紅底黑字就會乖乖出現在畫面正中央。掌握「宣告屬性 → 讀取屬性 → onDraw 繪製」這三步,之後任何自製控制項都能照樣複製。

想再深入的朋友,可以延伸閱讀本站《Android 開發入門與進階教程》《Android 基本組件用法總結》《Android 視圖 View 技巧總結》《Android 布局 layout 技巧總結》等專題。

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