これはしばらくの間私を悩ませてきましたが、検索しても結果が得られませんでした。カスタム GUI 要素がある場合は、LayoutInflater を使用して、通常のコンポーネントと同じようにインフレートできます。インフレーション呼び出しにより、カスタム GUI 要素のコンストラクターが呼び出され、すべて問題ありません。
しかし、要素のコンストラクターにカスタム パラメーターを追加したい場合はどうすればよいでしょうか? LayoutInflater を使用してこのパラメータを渡す方法はありますか?
例えば:
メイン xml には、レイアウト用のホルダーがあります。
<LinearLayout
android:id="@+id/myFrameLayoutHolder"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
および MyFrameLayout.xml ファイル:
<com.example.MyFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MyFLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1 >
<!-- Cool custom stuff -->
</com.example.MyFrameLayout>
そしてインフレータ呼び出し:
LayoutInflater MyInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout myFLayoutHolder = (LinearLayout) findViewById(R.id.myFrameLayoutHolder);
MyFrameLayout L = ((MyFrameLayout) MyInflater.inflate(R.layout.MyFLayout, myFLayoutHolder, false));
myFLayoutHolder.addView(L);
FrameLayout を拡張するクラスで、コンストラクターにパラメーターを追加すると、クラッシュが発生します。
public class MyFrameLayout extends FrameLayout {
private int myInt;
public MyFrameLayout(Context context) {
this(context, null);
}
public MyFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0, 0);
}
public MyFrameLayout(Context context, AttributeSet attrs, int defStyle, int myParameter) {
super(context, attrs, defStyle);
myInt = myParameter;
//Amazing feats of initialization
}
}
レイアウトのインフレーションの直後に呼び出すカスタム init メソッドを定義することで、この問題を回避するのは簡単ですが、それは私には不器用に思えます。より良い方法はありますか?