Search code examples
androidandroid-fragmentsandroid-activity

Best Practice for Accessing a View in an Activity from a Fragment?


I'm seeking clarification on a fundamental concept. How do you best access a view that's in an activity from a fragment?

Currently, I know of two methods:

Using the fragment to call the activity's findViewById .

Making the binding public and accessing it like: activity.binding.example .

Which of these is considered best practice, or is there another more efficient way?


Solution

  • The downsides with your two approaches is that it tightly couples the activity and the fragment. If you decide later that your fragment needs to be hosted by more than one activity, you will run into problems. Using interfaces can help with that, but only to a point.

    A more flexible solution is to create small dedicated viewmodel class representing the bridge between the fragment and the activity. If you set that up as a shared viewmodel, the fragment and the activity will share the instance. Then, you can use typical reactive communications (LiveData, RxJava, Kotlin Flow, etc.) to have the fragment indirectly update the activity's state. Now, all a consumer (activity, parent fragment, peer fragment) need to do is share the same viewmodel and observe the reactive state, then update their UIs to match.