Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View constructor in Android 4.4 crashes on Kotlin, how to fix?

I have a custom view written in Kotlin using JvmOverloads that I could have default value.

class MyView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0,
    defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyle, defStyleRes)

All works fine in Android 5.1 and above.

However it crashes in 4.4, since the constructor in 4.4 doesn't have defStyleRes. How could I have that supported that in 5.1 and above I could have defStyleRes but not in 4.4, without need to explicitly having 4 constructors defined like we did in Java?

Note: The below would works fine in 4.4, but then we loose the defStyleRes.

class MyView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle)
like image 604
Elye Avatar asked Jul 28 '17 05:07

Elye


3 Answers

I got a way of doing so. Just overload the first 3 functions will do, leave the 4th one for Lollipop and above wrap with @TargetApi.

class MyView : LinearLayout {
    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
        : super(context, attrs, defStyleAttr)

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)
        : super(context, attrs, defStyleAttr, defStyleRes)
}
like image 121
Elye Avatar answered Oct 21 '22 21:10

Elye


Best way is to have your class this way.

class MyView : LinearLayout {
    @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr)
    @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
}
like image 25
Seaskyways Avatar answered Oct 21 '22 19:10

Seaskyways


Just define the constructors like this:

constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@TargetApi(21)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
like image 1
EpicPandaForce Avatar answered Oct 21 '22 20:10

EpicPandaForce