Custom View constructor in Android 4.4 crashes on Kotlin, how to fix?

后端 未结 3 1416
小蘑菇
小蘑菇 2021-02-08 09:05

I have a custom view written in Kotlin using JvmOverloads that I could have default value.

class MyView @JvmOverloads constructor(
    context: Context,
    attr         


        
相关标签:
3条回答
  • 2021-02-08 09:28

    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)
    }
    
    0 讨论(0)
  • 2021-02-08 09:32

    I got a way of doing so. Just overload the first 3 functions will do, leave the 4th one for Lollipop and above wrap with @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 讨论(0)
  • 2021-02-08 09:45

    Just define the constructors like this:

    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)
    
    0 讨论(0)
提交回复
热议问题