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 trial

Android Android Fragments Introducing Fragments Handling Clicks

Sexual Potatoes
Sexual Potatoes
12,051 Points

Why do we need to go back to the ListFragment class, get the activity and cast it onto the interface?

I didn't understand the reasoning behind anything past creating the interface and implementing it correctly in MainActivity.java. There wasn't much of an explanation either. What role does this part play in the process ?

1 Answer

You want to send a message to MainActivity from ListFragment.

You can't just do something like

MainActivity.doSomeMethod()

Instead, using an Interface is one way of creating a communication tunnel (one way) from Fragment to MainActivity. You cast the Interface with

getActivity()

because you need to specify which activity should recieve the message/callback.

Remember, this is only communication FROM Fragment TO MainActivity. If you want to communicate from MainActivity to Fragment, you will need to do something else, like use the FragmentManager.