Androidでattrs.xmlを使用してカスタム属性を定義する

Androidのビューにはandroid:idandroid:layout_widthなどの標準属性がありますが、attrs.xmlファイルを利用すると独自の属性を定義できます。この記事ではカスタムビューにattrs.xmlで定義した属性を適用する方法を解説します。

attrs.xmlの作成

res/values/attrs.xmlに以下の内容を作成します:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomTextView">
        <attr name="customColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>    
</resources>
この定義ではCustomTextViewというスタイル可能な要素を宣言し、色値用のcustomColorと寸法値用のtextSizeを属性として定義しています。

レイアウトファイルでの使用

以下のようにXML名前空間を宣言してカスタム属性を使用します:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.CustomTextView
        android:id="@+id/custom_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:customColor="#FFD700"
        app:textSize="24sp" />
</RelativeLayout>
res-autoを使用することでパッケージ名に依存しない名前空間が利用可能になります。

カスタムビューの実装

属性値を取得するコンストラクタを実装します:
public class CustomTextView extends View {
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
        
        int textColor = typedArray.getColor(R.styleable.CustomTextView_customColor, Color.RED);
        float fontSize = typedArray.getDimension(R.styleable.CustomTextView_textSize, 16);
        
        // 取得した値をペイントオブジェクトに設定
        Paint paint = new Paint();
        paint.setColor(textColor);
        paint.setTextSize(fontSize);
        
        typedArray.recycle(); // リソース解放
    }
}
TypedArrayを通じて属性値を取得し、デフォルト値を第二引数で指定します。recycle()メソッドでリソースを解放する処理を忘れないようにしてください。

動作原理

1. R.styleable.CustomTextViewで属性配列を取得 2. 各属性の型に応じたメソッド(getColor/getDimension)で値を抽出 3. 取得した値をビューの描画処理に適用 4. recycle()でメモリリーク防止のための後片付け この方法によりテーマやスタイリングを通じた柔軟な属性制御が可能になります。

タグ: Android attrs.xml カスタム属性 カスタムビュー TypedArray

5月17日 09:57 投稿