21

i'm newbie i have problem creating game

execute process

activity_main.xml -> MainActivity.java -> GameLoop.java -> action.xml (error) -> CustomView.java

Custom view CustomView is not using the 2- or 3-argument View constructors; XML attributes will not work

I don't understand......

4

4 に答える 4

58

CustomView で View の他の 2 つのコンストラクターをオーバーライドする必要があります。

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 context) {
    //do stuff that was in your original constructor...
}
于 2012-12-10T08:39:26.120 に答える
11

これらのコンストラクターも実装する必要があります。

//Constructor that is called when inflating a view from XML.
View(Context context, AttributeSet attrs)

//Perform inflation from XML and apply a class-specific base style.
View(Context context, AttributeSet attrs, int defStyle)
于 2012-12-10T08:40:01.170 に答える
1

カスタムビューの作成方法と使用方法に依存すると思います。
3 つのコンストラクターすべてが実際に必要なわけではありません。
属性 xml ファイルを使用してビューを作成するが、defstyle を使用しない場合は、呼び出すだけで十分です。

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs);
    //Your code
}

属性と defstlye を使用していない場合 /私はこれの例を見ました/

public CustomView(Context context) {
    super(context);
    //Your code
}

そして、defstyleと属性も使用したい場合

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs);
    //Yourcode
}
于 2014-03-09T09:05:08.503 に答える
0

誰かが Kotlin で作業している場合、彼/彼女はそれを行うことができます:

class KotlinView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr)

このソリューションと詳細については、https ://antonioleiva.com/custom-views-android-kotlin/ を参照してください。

于 2020-05-28T09:42:25.153 に答える