0

I'm trying to extend android.widget.FrameLayout in my class in kotlin. The problem is that since I upgraded to kotlin 1.2.21 I can't compile because the longest(4 arguments) constructor of FrameLayout requires minSdk 21, but my lib needs to work on api level 19 as well. I already gave up on using the @JvmOverloads (it seems to be buggy and Instant Run crashes) so I try to write the "long" code. Something like:

First way I tried:

class PullDownAnimationLayout : FrameLayout, Animator.AnimatorListener, PullDownAnimation {
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) :
            super(context, attrs, defStyleAttr, defStyleRes)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
            super(context, attrs, defStyleAttr)
    constructor(context: Context, attrs: AttributeSet?) :
            this(context, attrs, 0)
    constructor(context: Context) :
            this(context, null)

    override val MAX_PULL_HEIGHT_PX: Int
    override val REFRESH_TRIGGER_HEIGHT_PX: Int

    init {
        initFoo(attrs) // ERROR: Unresolved reference: attrs
        MAX_PULL_HEIGHT_PX = dpToPx(MAX_PULL_HEIGHT_DP)
        REFRESH_TRIGGER_HEIGHT_PX = dpToPx(REFRESH_TRIGGER_HEIGHT_DP)
    }

The problem in this version is that init doesn't see attrs: Unresolved reference: attrs

So here's a second way I tried by adding the 3-args constructor as primary constructor:

class PullDownAnimationLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
            FrameLayout(context, attrs, defStyleAttr), Animator.AnimatorListener, PullDownAnimation {
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) :
            super(context, attrs, defStyleAttr, defStyleRes) // ERROR: Primary constructor call expected
    constructor(context: Context, attrs: AttributeSet?) :
            this(context, attrs, 0)
    constructor(context: Context) :
            this(context, null)

    override val MAX_PULL_HEIGHT_PX: Int
    override val REFRESH_TRIGGER_HEIGHT_PX: Int

    init {
        initFoo(attrs)
        MAX_PULL_HEIGHT_PX = dpToPx(MAX_PULL_HEIGHT_DP)
        REFRESH_TRIGGER_HEIGHT_PX = dpToPx(REFRESH_TRIGGER_HEIGHT_DP)
    }
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • How about putting `initFoo(attrs)` inside the 3-args constructor (1st approach)? – BakaWaii Jan 25 '18 at 16:29
  • Tried it but it didn't work because I do some val initialisations in init – Gavriel Jan 25 '18 at 17:00
  • Possible duplicate of [Custom View constructor in Android 4.4 crashes on Kotlin, how to fix?](https://stackoverflow.com/questions/45365651/custom-view-constructor-in-android-4-4-crashes-on-kotlin-how-to-fix) – max Sep 11 '18 at 06:43

0 Answers0