Android Viewの独自のパラメータdeclare-styleableをどのように使用するか?

Androidでは、declare-styleableを使用してカスタムビューの属性を定義することができます。declare-styleableは、カスタムビューの属性セットを定義するためのXMLタグです。

以下はdeclare-styleableの使用手順です:

  1. res/values/attrs.xml – 属性.xml
  2. デクレアスタイル可能
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="titleText" format="string" />
        <attr name="subtitleText" format="string" />
        <attr name="titleTextColor" format="color" />
        <attr name="subtitleTextColor" format="color" />
    </declare-styleable>
</resources>
  1. 以下の情報を取得するStyledAttributes
public class MyCustomView extends View {
    private String titleText;
    private String subtitleText;
    private int titleTextColor;
    private int subtitleTextColor;
    
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
        
        titleText = a.getString(R.styleable.MyCustomView_titleText);
        subtitleText = a.getString(R.styleable.MyCustomView_subtitleText);
        titleTextColor = a.getColor(R.styleable.MyCustomView_titleTextColor, Color.BLACK);
        subtitleTextColor = a.getColor(R.styleable.MyCustomView_subtitleTextColor, Color.GRAY);
        
        a.recycle();
    }
    
    // ...
}

上記の例では、obtainStyledAttributesメソッドは、attrs.xmlで定義された属性値を取得し、それをtitleText、subtitleText、titleTextColor、subtitleTextColorに代入します。

  1. レイアウトファイルでカスタムビューを使用し、プロパティ値を設定する。
<com.example.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:titleText="Title"
    app:subtitleText="Subtitle"
    app:titleTextColor="#FF0000"
    app:subtitleTextColor="#00FF00" />

上記の例では、app:接頭辞を使用してカスタム属性の値を設定します。

これにより、declare-styleableを使用してカスタムViewの属性を定義および使用することができます。

bannerAds