Android Viewのカスタムパラメータを宣言する
Androidにおいて、Viewの機能を拡張するためには、カスタムViewクラスでカスタム属性を宣言することができます。以下はカスタムViewのパラメータ宣言の一般的な手順です。
- res/values/attrs.xmlファイルでカスタム属性を宣言する。
<resources>
<declare-styleable name="CustomView">
<attr name="customAttribute" format="integer" />
</declare-styleable>
</resources>
上記のコードでは、”customAttribute”というカスタム属性を宣言し、整数の形式を指定しました。
- 自作Viewクラスのコンストラクタ内で、カスタム属性を取得して適用する。
public class CustomView extends View {
private int customAttribute;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customAttribute = typedArray.getInteger(R.styleable.CustomView_customAttribute, defaultValue);
typedArray.recycle();
// 在这里可以根据customAttribute的值进行相关操作
}
// ...
}
上記のコードでは、TypedArrayからobtainStyledAttributes()メソッドを使用してカスタム属性の値を取得し、その値をカスタムViewクラス内の変数customAttributeに保存しています。値を取得する際には、R.styleable.CustomView_customAttributeを属性の参照として使用し、CustomViewはattrs.xmlで宣言されているカスタム属性セットの名前であり、customAttributeはその中で宣言されている属性の名前です。defaultValueは、その属性に値が提供されていない場合のデフォルト値です。
- レイアウトファイルでカスタム属性を使用する。
<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttribute="123" />
上記のコードでは、CustomViewというカスタムビューをレイアウトファイルで使用し、customAttributeプロパティを123に設定しました。
以上の手順を経て、カスタムView内でカスタム属性を使用してViewの機能を拡張することができます。