Android カスタムビューは宣言型で生成する
Android では `declare-styleable` を使用することでカスタムビューの属性を定義して使うことができます。簡単な例を以下に示します。
res/values/attrs.xml ファイルでカスタム属性を宣言します。
<resources>
<declare-styleable name=”CustomView”>
<attr name=”customText” format=”string” />
<attr name=”customColor” format=”color” />
<!– 添加其他自定义属性 –>
</declare-styleable>
</resources>
このサンプルでは、CustomViewというスタイル定義を作成し、その中で、カスタムText(文字列型)とカスタムカラー(カラー型)という2つのカスタム属性を宣言する。
レイアウトファイルでカスタムコントロールを使用し、カスタム属性を設定します。
<com.example.myapp.CustomView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
app:customText=”Hello, World!”
app:customColor=”@color/blue” />
本例では、CustomView というカスタムコントロールを使用し、 app:customText と app:customColor 属性でカスタムプロパティの値を設定しています。
カスタマイズされたアトリビュートを独自コントロールクラスで取得して使用します。
public class CustomView extends View {
private String customText;
private int customColor;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customText = a.getString(R.styleable.CustomView_customText);
customColor = a.getColor(R.styleable.CustomView_customColor, 0);
a.recycle();
// 使用customText和customColor进行相应操作
}
}
この例では、TypedArrayを用いて CustomView クラスのコンストラクタでカスタム属性の値を取得し解析しています。R.styleable.CustomView_customText と R.styleable.CustomView_customColor で対応する属性の添字を取得し、その後、a.getString() と a.getColor() メソッドで属性の値を取得しています。
カスタマイズされたコントロールクラス内で、ニーズに応じてこれらカスタムプロパティの値をさらに処理し、コントロール内で適切な操作を実行できます。