22

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......

xsxy
  • 231
  • 1
  • 2
  • 4

4 Answers4

60

You need to override the other 2 constructors of View in CustomView:

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...
}
Andy McSherry
  • 4,676
  • 3
  • 26
  • 36
  • changed this code action.xml error now.Study.androidproject.CustomView failed to instantiate. java.lang.StackOverflowError – xsxy Dec 10 '12 at 09:25
  • The following classes could not be instantiated: - now.Study.androidproject.CustomView (Open Class, Show Error Log) See the Error Log (Window > Show View) for more details. Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse – xsxy Dec 10 '12 at 09:25
  • err... sorry i left a call to init() in the init function, probably a stack overflow error, corrected now – Andy McSherry Dec 10 '12 at 09:46
  • Where should I add this? – Si8 Aug 20 '13 at 19:00
  • The 2nd constructor calls init twice. – Nick Westgate Mar 15 '14 at 13:11
11

You need to implement these constructors also:

//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)
Trevor
  • 10,903
  • 5
  • 61
  • 84
1

I think it depends how You creating Your custom view and how You gonna use it .
Not all 3 constructors really necessary.
If You create the view with attributes xml file, but won't use defstyle, its enough to call

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

if You not using attributes and defstlye /i saw examples for this/ You happy to call only

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

and if You want use defstyle and attributes too

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs);
    //Yourcode
}
bianchi
  • 11
  • 2
0

In case someone works with Kotlin he/she can do that:

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

You can find this solution and more details here: https://antonioleiva.com/custom-views-android-kotlin/

Tzegenos
  • 837
  • 12
  • 16