I have a base class that I am extending, but want to inflate a view where the normal Java constructor would be.
class TextView(context: Context?) : ViewAbstractClass(context)
I am not sure how to do this in Kotlin. What are the constructs are there Kotlin that allow you to do complex initialisation of objects?
https://kotlinlang.org/docs/reference/classes.html#constructors
class Customer(name: String) {
init {
logger.info("Customer initialized with value ${name}")
}
}
There are a couple ways this can be done, however this is what I've been doing in my app.
class TextView : ViewAbstractClass {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) {
// custom init code for this constructor.
}
constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attributeSet, defStyleAttr, defStyleRes)
init {
// Common init code
}
}
Notice that you don't actually use () in the class signature, but instead provide all the constructors explicitly.
You can learn more about secondary constructors here: https://kotlinlang.org/docs/reference/classes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With