How can I use the same constructors in different classes and also define constructors in an interface?

Let's say I have multiple custom views in Android with the same constructors

class Button: AppCompatButton {

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    }

    constructor(context: Context) : super(context) {
    }
    //Some custom implementation
    //............
}

class TextView: AppCompatTextView {

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    }

    constructor(context: Context) : super(context) {
    }
    //Some custom implementation
    //............
}

      

So I need some kind of interface or base class that allows me to inherit several kinds of views like TextView, Button, EditText, etc.

Something like

abstract class BaseView<T : View> : T {
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    }

    constructor(context: Context) : super(context) {
    }
}

      

or

interface ViewConstructor {
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    }

    constructor(context: Context) : super(context) {
    }
}

      

So, I just use one interface or base class and don't copy past contractors over and over. How to achieve this goal in Kotlin?

PS Don't suggest using the base class as a view and create derived views using the base class. I am using XML and I need EditText, Button and other views as they are.

+3


source to share


2 answers


As a solution to writing many constructors, you can use default arguments in combination with @JvmOverloads

to easily get all 4 constructors by View

just writing the primary constructor for your class:



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

}

      

+4


source


It is extremely unlikely that you will find a solution to your problem. For example, constructors are not inherited in the way you suggest. They exist to initialize your part of the inheritance chain, so anyone who inherits from you will still have to forward the superclass constructor. I'm pretty sure you're stuck with updating these view constructors in every View class (although some of them you could probably give up on your instance use case).



0


source







All Articles