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

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

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

在Android 5.1及以上版本中,所有工作都很好。

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

注意:下面的4.4可以正常工作,但是我们defStyleResdefStyleRes

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

最好的方法是让你的班级这样。

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

我有一个这样做的方法。 只是超载的前3个功能将做,离开第四个棒棒糖和以上包装@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) }