Androidにてプログラム的にViewを作成する際にAttributeSetを利用する方法は?

カスタムビューへ AttributeSet を送るには、Android では以下を使用します。

  1. カスタムコンストラクタの使用: Context オブジェクトと AttributeSet オブジェクトを引数として受け取るカスタムビュー用のコンストラクタを作成します。コンストラクタ内では super メソッドを呼び出すことで親のコンストラクタに AttributeSet を渡します。
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// 进行其他初始化操作
}
}
  1. LayoutInflaterのinflate()メソッドを使用: カスタムビューがレイアウトファイルからロードされた場合、LayoutInflaterのinflate()メソッドを使用してAttributeSetをビューに渡すことができます。
LayoutInflater inflater = LayoutInflater.from(context);
CustomView customView = (CustomView) inflater.inflate(R.layout.custom_view, parentView, false);

レイアウトファイルでは、ルートビューにカスタム属性を設定することでAttributeSetを渡すことができます。

<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:customAttribute="value" />
  1. テーマから属性を使用する:テーマから属性値を取得してカスタムビューに渡すには、TypedArrayオブジェクトを使用します。
TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0);
int customAttributeValue = typedArray.getInt(R.styleable.CustomView_customAttribute, defaultValue);
typedArray.recycle();

カスタム属性は、カスタムViewの attr.xml ファイルで定義する必要があります。

<resources>
<declare-styleable name="CustomView">
<attr name="customAttribute" format="integer" />
</declare-styleable>
</resources>
bannerAds