34

私は以下からカスタムビューの使用について学んでいます:

http://developer.android.com/guide/topics/ui/custom-components.html#modifying

説明は言う:

クラスの初期化いつものように、スーパーが最初に呼び出されます。さらに、これはデフォルトのコンストラクターではなく、パラメーター化されたコンストラクターです。EditTextは、XMLレイアウトファイルからインフレートされたときにこれらのパラメーターを使用して作成されるため、コンストラクターはこれらのパラメーターを取得して、スーパークラスコンストラクターにも渡す必要があります。

より良い説明はありますか?私はコンストラクターがどのように見えるべきかを理解しようとしていて、4つの可能な選択肢を考え出しました(投稿の最後にある例を参照してください)。これらの4つの選択肢が何をするのか(またはしないのか)、なぜそれらを実装する必要があるのか​​、またはパラメーターの意味がわかりません。これらの説明はありますか?

public MyCustomView()
{
    super();
}

public MyCustomView(Context context)
{
    super(context);
}

public MyCustomView(Context context, AttributeSet attrs)
{
    super(context, attrs);
} 

public MyCustomView(Context context, AttributeSet attrs, Map params)
{
    super(context, attrs, params);
} 
4

3 に答える 3

66

最初のものは必要ありません。それはうまくいかないからです。

3 つ目は、カスタムViewが XML レイアウト ファイルから使用できることを意味します。そこまで気にしないなら要らない。

4番目は間違っています、AFAIK。3 番目のパラメーターとしてViewa を取るコンストラクターはありません。ウィジェットのデフォルト スタイルをオーバーライドするために使用される、3 番目のパラメータとして を受け取るものがありますMapint

this()これらを組み合わせるには、次の構文を使用する傾向があります。

public ColorMixer(Context context) {
    this(context, null);
}

public ColorMixer(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ColorMixer(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // real work here
}

この本の例で、このコードの残りの部分を見ることができます。

于 2010-05-22T15:07:12.507 に答える
11

これが私のパターンです(ViewGoupここでカスタムを作成しますが、それでも):

// CustomView.java

public class CustomView extends LinearLayout {

    public CustomView(Context context) {
        super(context);
        init(context);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context ctx) {
        LayoutInflater.from(ctx).inflate(R.layout.view_custom, this, true);
            // extra init
    }

}

// view_custom.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Views -->
</merge>
于 2012-06-02T15:39:00.610 に答える