[英]Custom View constructor in Android 4.4 crashes on Kotlin, how to fix?
我有一個使用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,而不需要像在Java中那樣明確地定義4個構造函數?
注意:以下在4.4中可以正常工作,但是我們松開了defStyleRes
。
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個函數就可以了,留下第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)
}
只需像這樣定義構造函數:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.