Android 4.4中的自定义视图构造函数在Kotlin上崩溃,如何修复?

Ely*_*lye 11 android android-custom-view kotlin android-4.4-kitkat

我有一个使用JvmOverloads在Kotlin中编写的自定义视图,我可以使用默认值.

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

Android 5.1及以上版本均可正常使用.

然而它在4.4中崩溃,因为4.4中的构造函数没有defStyleRes.我怎么能支持在5.1及以上版本中我可以拥有defStyleRes但不在4.4中,而不需要像在Java中那样明确地定义4个构造函数?

注意:以下在4.4中可以正常工作,但之后我们就松了defStyleRes.

class MyView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle)
Run Code Online (Sandbox Code Playgroud)

Sea*_*ays 12

最好的方法是让你的课程这样.

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)
}
Run Code Online (Sandbox Code Playgroud)


Ely*_*lye 6

我有办法这样做.只需重载前3个函数就可以了,留下第4个用于Lollipop以及上面用@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)
}
Run Code Online (Sandbox Code Playgroud)