2017-07-28 43 views
7

我有一個使用JvmOverloads在Kotlin編寫的自定義視圖,我可以使用默認值。Android 4.4中的自定義視圖構造函數在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會正常工作,但是我們放棄了defStyleRes

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

回答

6

最好的方法是讓你的班級這樣。

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

這回有定義的所有4個構造:( – Elye

+0

那麼它就是這樣的Android作品,不管多少科特林的語法如何幫助,這是Android的需要樣板之一的老辦法:d不管怎麼說,你可以修剪這些使用默認值,但你必須使用至少2個構造函數 – Seaskyways

+0

@Elye我已編輯我的答案,以顯示與2構造函數相同的功能 – Seaskyways

4

我有辦法這樣做。只是超載的前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) 
} 
+0

這是一個有效的答案。好@Elye –

相關問題