Reputation: 166
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)
Upvotes: 0
Views: 3306
Reputation: 8106
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)
...
}
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)
}
Upvotes: 1
Reputation: 1929
lateinit var binding: pendaftaranBinding
init {
binding = DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)
}
or
You can use binding delegate please read: this if you want to use val instead of var
Upvotes: 2
Reputation: 3502
so that it can be accessed for all methods
If I understood correctly, you mean that you want to access a pendaftaranBinding
type variable in other methods, then you simply declare that variable in the class's body.
Example:
class YourActivity : AppCompatActivity() {
private lateinit var yourBinding: pendaftaranBinding
override fun onCreate() {
yourBinding = DataBindingUtil.inflate(inflater, R.layout.pendaftaran, container, false)
}
private fun yourOtherMethod() {
yourBinding.yourView
}
}
Upvotes: 3