Search code examples
androidstaticandroid-viewbinding

Is it possible to use view binding in a static method?


My question is, if it is possible to use view binding in a static method:

class SomeFragment : FragmentBinding<SomeFragmentBinding>() {

 companion object {
   fun someRandomFunction() {
    // Use view binding here
    binding.textView.text = "Test"
   }
 }
}

Solution

  • binding is a non-static property of SomeFragment class, where as companion object are static. Static methods cannot access non-static properties, because each instance of the class would have their own instances of that non-static property.

    So, you cannot access binding or any other non-static property inside companion object.