Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialErrol Gonzales
20,948 PointsCommunication between Activity and Fragment
What is the best way to communicate to Activity from fragment? Is it by defining an interface? or by using getActivity() then call a public function from that activity. something like this: ((MainActivity)getActivity()).doThis();
which is better? because both of them are working. Defining interface is just have a lot of codes. thanks.
1 Answer
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsI think the best way is through the interface.
The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity. Once Fragment has implemented the interface, you could do anything you want inside the Override methods declared by the interface. For example, inside the override methods you can create new fragment or start a new intent.
It is much cleaner this way.