2

With view binding being the recommended way to access the view this question becomes obsolete: How to access parent Activity View in Fragment.

So, what is the correct way to edit the activity view from fragment using view binding?

Smeagol
  • 593
  • 9
  • 23
  • It depends on what you need it for (e.g. a reference, an instance, the creating instance, etc.) As in any large framework, you can acquire most resources in multiple ways, but each method usually returns a different version of it, usually tailored to a certain (set of) use-case(s)... In other words, what do you need it for? : ) – Nate T May 26 '21 at 13:55
  • ViewBinding has nothing to do with data sharing between two entities (activities, fragments, etc.) The Google recommended approach is to use a shared ViewModel if you really need to access a shared state. – Martin Marconcini May 26 '21 at 14:27

2 Answers2

4

Make binding variable of activity public and access it like this

(requireActivity() as MainActivity).binding.viewToBeAccessed

Praveen
  • 3,186
  • 2
  • 8
  • 23
0

You can use getActivity() to get a reference to parent activity from fragment. You can also call requireActivity() which in turn calls getActivity() and throws exception if its null, e.g. the fragment is not attached to any activity.

Ara Mkrtchyan
  • 497
  • 6
  • 12