本文介绍了Android 4.4中的Custom View构造函数在Kotlin上崩溃,该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

在Android 5.1及更高版本中,一切正常.

All works fine in Android 5.1 and above.

但是它在4.4中崩溃,因为4.4中的构造函数没有defStyleRes.我该如何支持5.1及更高版本中的defStyleRes而不是4.4中的defStyleRes,而无需像我们在Java中那样显式定义4个构造函数?

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?

注意:以下内容在4.4中可以正常使用,但随后我们松开defStyleRes.

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)

推荐答案

最好的方法是以这种方式创建您的课程.

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)
}

这篇关于Android 4.4中的Custom View构造函数在Kotlin上崩溃,该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 08:50