カスタムビューを作る

提供: tknotebook
2015年9月21日 (月) 05:38時点におけるNakamuri (トーク | 投稿記録)による版

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

メインページ>コンピュータの部屋#Android>Android Tips


Android には標準で Button や TextView や LinearLayout など、多数のビューを利用できますが、ビューを自作することもできます。

以下に楕円を表示するだけの簡単なビューの実装例を示します。

モジュールを作成する

AndroidStudio で作成する場合は、専用の Android Library Module を新規に作るのがよいでしょう。

カスタム属性を定義する

モジュールに res/values/attr.xml というファイルを作り、カスタム属性を定義します。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Ellipse">
        <attr name="strokeColor" format="color"/>
        <attr name="strokeWidth" format="dimension"/>
    </declare-styleable>
</resources>

strokeColor は楕円の輪郭の色、strokeWidth は楕円の輪郭の太さです。

カスタムビューのクラスを作成する

カスタムビューのクラスを View クラスを継承して作成します。名前は Ellipse としましょう。

class Ellipse extends View {
    // 輪郭色。既定値は赤
    private int mStrokeColor = Color.RED;
    // 輪郭幅。
    private float mStrokeWidth;
    // 楕円のサイズ
    private final RectF rect = new RectF();
    // 描画用Paint
    private final Paint mPaint = new Paint();

 :
 :
}

コンストラクタを書く

コンストラクタは2種類必要です。

    public Ellipse(Context context) {
        this(context, null);
    }


    public Ellipse(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 160dpiとの比を求める。
        float mDensity = getContext().getResources().getDisplayMetrics().density;
        // 線幅を既定値 2dp に。
        mStrokeWidth = (int) (mDensity * 2); 

         if (attrs == null) {
            return;
        }

        // 楕円の属性を取得
        TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.Ellipse);
        try {
            // 色と高さを設定
            mStrokeColor = tArray.getColor(R.styleable.Ellipse_strokeColor, mStrokeColor);
            mStrokeWidth = tArray.getDimensionPixelSize(R.styleable.Ellipse_strokeWidth, mStrokeWidth);
        } finally {
            tArray.recycle();
        }
    }

XMLで指定されたカスタムアトリビュートは AttributeSet attrs という引数で入力されてきますが、そのまま使ってはいけません。 コンテキストのobtainStyledAttributesメソッドで TypedArray 型に変換してください。これで属性はテーマやスタイルが反映された正しい値になります。

カスタム属性は TypedArray の getColorメソッドなどに、R.styleable に自動生成された識別子を指定して値を取り出します。 カスタム属性値がない場合、getColorなどのメソッドの最後のパラメータが既定値として戻るのに注意してください。従って mStrokeWidthやmStrokeColorは予め規定値で初期化しておく必要があります。

カスタム属性の setter/getter を用意する

XMLで設定できる属性は通常コードからも動的に設定できるようにします。

以下、鋭意作成中