Reputation: 87
In the MainActivity
class I use this snippet:
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
And I'm trying to access textView from other class like this
MainActivity().binding.textView.text
but I'm getting lateinit property binding has not been initialized
error on this line? Anyone knows how to solve it?
Upvotes: 2
Views: 2129
Reputation: 815
When you you're calling MainActivity(), you're effectively creating a new instance of MainActivity, but it hasn't been bound to any lifecycle (thus not calling onCreate(), thus not inflating your layout).
If you're trying to access the activity from a fragment, call:
(requireActivity() as MainActivity).binding.textView.text
Edit: do note that this approach will throw an error if your fragment is hosted by a different activity than MainActivity
Upvotes: 4