Reputation: 40255
I was trying to implement CustomView
in Kotlin
, which is to be used both for programatically and for statically. Thus, I need to override both versions of constructors.
For programatically I use version,
class CustomView @JvmOverloads constructor(
context: Context,
) : View(context)
For statically I use version,
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : View(context, attrs)
How can I change it for overriding multiple versions under same class which then I can instantiate from static views as well as programatically?
There are some post on constructors i.e. Kotlin secondary constructor which does not help for overriding multiple versions of constructor.
Upvotes: 1
Views: 1331
Reputation: 11487
This should work both programatically and statically :-
class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr)
Programatically just call :-
CustomView(context) // passing other params to constructor is not mandatory..
Upvotes: 1
Reputation: 111
I created this code to recreate your issue:
Test.java
:
public class Test {
private int i ;
private String name;
public Test(int i) {
this.i = i;
name = "test";
}
public Test(int i, String name) {
this.i = i;
this.name = name;
}
}
TestK.kt
:
class TestK : Test {
constructor(i: Int, name: String): super(i, name)
constructor(i: Int) : super(i)
}
As you can see, I'm overloading the parents constructor with different parameter amounts.
Upvotes: 1