Androidでdeclare-styleable属性の使い方

Android開発では、declare-styleable属性は、カスタム属性セットを定義し使用し、レイアウトファイルやコード内で利用することを目的としています。以下はdeclare-styleable属性を使用する手順です。

  1. res/values/attrs.xmlファイルで属性集合を定義します。
<resources>
    <declare-styleable name="CustomView">
        <attr name="customAttribute1" format="string" />
        <attr name="customAttribute2" format="integer" />
        ...
    </declare-styleable>
</resources>
  1. レイアウトファイルでカスタムプロパティを使用
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.example.CustomView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:customAttribute1="value1"
        app:customAttribute2="value2" />

</LinearLayout>
  1. カスタムViewクラスで属性値を取得して使用する:
public class CustomView extends View {
    private String customAttribute1;
    private int customAttribute2;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
        customAttribute1 = a.getString(R.styleable.CustomView_customAttribute1);
        customAttribute2 = a.getInt(R.styleable.CustomView_customAttribute2, 0);
        a.recycle();
    }
    
    // 使用属性值
    // ...
}

上で示したコードでは、context.obtainStyledAttributesメソッドでアトリビュート集合を取得し、R.styleable.CustomView_customAttribute1とR.styleable.CustomView_customAttribute2で対応するアトリビュートのインデックスを検索しています。getStringやgetIntメソッドを使ってアトリビュートの具体的な値を取得し、最後にrecycleメソッドを呼び出してTypedArrayを解放しています。

これにより、ユーザー定義 View で declare-styleable 属性を使用できるようになります。

bannerAds