.java not using the 2- or 3-argument View constructors; XML attributes will not work

后端 未结 4 709
不知归路
不知归路 2020-12-09 04:10

i\'m newbie i have problem creating game

execute process

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

相关标签:
4条回答
  • 2020-12-09 04:28

    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/

    0 讨论(0)
  • 2020-12-09 04:41

    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
    }
    
    0 讨论(0)
  • 2020-12-09 04:43

    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...
    }
    
    0 讨论(0)
  • 2020-12-09 04:49

    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)
    
    0 讨论(0)
提交回复
热议问题