androidkotlinandroid-custom-viewandroid-attributes

Accessing attrs in custom view in Kotlin


I am creating a custom view in Kotlin.

For the constructors, I have followed the suggestions listed here: https://blog.q42.nl/the-danger-of-assumptions-kotlin-with-android-custom-views-adb79bf2da45

My problem is that now the init block doesn't recognise the attrs parameter since they are not in the primary constructor.

Am I missing something?


Solution

  • Just make the constructors with bodies and call a function initialising attributes from within.

    For example:

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        attrs?.let { initAttrs(it) }
    }
    
    private fun initAttrs(attrs: AttributeSet) {
        ...
    }