Search code examples
kotlinmvvmviewmodel

how to initialize binding to be property (android viewmodel )?


I want the variable binding to be a property so that it can be accessed for all methods, but I don't know how to initialize it (kotlin)

 val binding: pendaftaranBinding=
        DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)

to

var binding: .........................
binding: pendaftaranBinding=
            DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)

Solution

  • To initialize the property in the init{} block

    You could assign the Type and then initialize it later after doing some tasks in the init{} block.

    val binding: pendaftaranBinding
    
    init{
        ...
        binding = DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)
        ...
    }
    
    

    To initialize it later on the code

    If you like not to initialize in the construction of the class, instead to initialize it later in the code, you could use lateinit modifier:

    lateinit var binding: pendaftaranBinding
    
    fun someFunction() {
        ...
        binding = DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)
        ...
    }
    

    so that it can be accessed for all methods

    I didn't understand this line, seems like you want something like static properties in java, initialize it outside the class. It could be done by using a companion object in kotlin:

    class YourClass {
        companion object {
            lateinit var binding: pendaftaranBinding
        }
    }
    
    fun initializeBinding() {
        YourClass.binding =
            DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)
    
    }