スタイルの宣言に使う

declare-styleableはXMLでカスタムビューの属性を定義するために使われるタグで、その使い方は次の通りです。

  1. カスタムViewの属性を定義するattrs.xmlファイルをres/valuesフォルダーに作成します。サンプルコードを以下に示します。
<resources>
<declare-styleable name="CustomView">
<attr name="customAttr1" format="string" />
<attr name="customAttr2" format="integer" />
</declare-styleable>
</resources>
  1. レイアウトファイルで独自ビューを使い、カスタム属性を取り入れる。サンプルコードは以下の通りです。
<com.example.CustomView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/customView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttr1="Hello"
app:customAttr2="123" />
  1. カスタムビューのコンストラクタでこれらの属性値を受け取ります。サンプルコードは以下のとおりです。
public class CustomView extends View {
private String customAttr1;
private int customAttr2;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customAttr1 = a.getString(R.styleable.CustomView_customAttr1);
customAttr2 = a.getInteger(R.styleable.CustomView_customAttr2, 0);
a.recycle();
}
}

declare-styleableを使って、カスタムビューの属性を簡単に定義して使用することができるため、カスタムビューの属性設定が柔軟で拡張性のあるものとなります。

bannerAds