Search code examples
javaandroidandroid-activitykotlinfragment

Communication between Fragment and Activity


The common way for a fragment to talk to its attached activity is via an interface. However, can we use the instance of the activity in that fragment?

For instance, we have a function named helloWorld() in MainActivity. And the MainActivity has a fragment called MainFragment. if I want to call the helloWorld() in MainFragment, I can get the instance of the MainActivity using (activity as MainActivity). Then, i can use this instance to invoke helloWorld.

So, it this a feasible way to achieve the communication; And also, it is a good way, or we still need to create an interface within the fragment and let the activity to implement that interface?


Solution

  • That works perfectly fine as long as you guarantee that your fragment is only ever used by that activity.