3

これはしばらくの間私を悩ませてきましたが、検索しても結果が得られませんでした。カスタム 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 メソッドを定義することで、この問題を回避するのは簡単ですが、それは私には不器用に思えます。より良い方法はありますか?

4

2 に答える 2

1

コンストラクターの署名が FrameLayout の独自のコンストラクターの署名と競合し、 を呼び出していないため、独自のパラメーターを使用してコンストラクターを定義することはできませんsuper(context, attrs, defStyle);。代わりにsuper(context, attrs);、このコンストラクターに対して不完全な を呼び出しています。

3 つのネイティブ コンストラクターをすべて、そのまま正確に定義する必要があります。

FrameLayout(Context context)
FrameLayout(Context context, AttributeSet attrs)
FrameLayout(Context context, AttributeSet attrs, int defStyle)

できることは、xml で独自の (カスタム) 属性を使用し、MyFrameLayout のattrsオブジェクトでそれらを取得することです。

于 2012-04-05T20:01:22.197 に答える
0

カスタム コンポーネントが XML ファイルまたは inflate メソッドによってインフレートされている場合。これはAndroidではサポートされていないため、コンストラクトに要素を渡さないでください。

于 2012-04-05T20:00:03.413 に答える