How to change view in parent activity from Fragment with view binding

Viewed 1011

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?

2 Answers

Make binding variable of activity public and access it like this

(requireActivity() as MainActivity).binding.viewToBeAccessed

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.

Related