Search code examples
androidandroid-custom-view

android customViews in kotlin - is it ok to initialize in the init block?


I am so confused why no one uses the init block in a android custom view to initialize and inflate the view. lets take an example of how i do this:

class MyCompoundView : ConstraintLayout {
    constructor(p0: Context) : super(p0)
    constructor(p0: Context, p1: AttributeSet?) : super(p0, p1)
    constructor(p0: Context, p1: AttributeSet?, p2: Int) : super(p0, p1, p2)

    init {
        inflate(context, R.layout.my_view_container, this)
//etc
    }

}

is there anything wrong with this as opposed to what i see all over the internet:

class MyCompoundView : ConstraintLayout {
    constructor(p0: Context) : super(p0){initialize()}

    constructor(p0: Context, p1: AttributeSet?) : super(p0, p1){initialize()}
    constructor(p0: Context, p1: AttributeSet?, p2: Int) : super(p0, p1, p2){initialize()}

 private fun initialize() {
        inflate(context, R.layout.ride_hail_otp_container, this)

    }

  }

ps. i do not favor jvmOverload in customViews so no need to mention that. just want to know about init block vs calling it in each constructor. i see no one doing it online and i wonder why ?


Solution

  • Yes, It's totally fine, I my self used this approach many times and ain't facing any problems.

    • one of the examples I'm currently working with :

      class MaterialSearchBar (context: Context, val attributeSet: AttributeSet) : Toolbar(context, attributeSet) {
          init {
          inflate(context, R.layout.material_search_toolbar, this)
          updateUi()
          requestFocus()
          setUpListeners()
          }
      
      //...
      
      }