Android用のカスタムコントロールでdeclare-styleableを使用してプロパティを設定
アンドロイドでは、declare-styleable を使用してカスタムビューの属性を定義して構成できます。以下に簡単な例を示します。
カスタム属性を定義するには、res/values フォルダに attrs.xml ファイルを作成します。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="customText" format="string" />
<attr name="customColor" format="color" />
<attr name="customSize" format="dimension" />
</declare-styleable>
</resources>
そしてレイアウトファイルでカスタムコントロールを使用し、関連プロパティを設定します。
<com.example.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customText="Hello"
app:customColor="@color/red"
app:customSize="16sp" />
次に、カスタムコントロールのクラス内でこれらのプロパティを取得して使用します:
public class CustomView extends View {
private String customText;
private int customColor;
private float customSize;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customText = typedArray.getString(R.styleable.CustomView_customText);
customColor = typedArray.getColor(R.styleable.CustomView_customColor, Color.BLACK);
customSize = typedArray.getDimension(R.styleable.CustomView_customSize, 12);
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 使用获取到的属性进行绘制
Paint paint = new Paint();
paint.setColor(customColor);
paint.setTextSize(customSize);
canvas.drawText(customText, 0, getHeight() / 2, paint);
}
}
このサンプルでは、カスタム属性である customText、customColor、customSize の 3 つを定義し、レイアウトファイルで設定しています。次に、これらの属性の値を取得するために CustomView クラスで TypedArray を使用し、それらの値を onDraw メソッドで描画操作に使用します。