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

interface (Fragements)

Can someone please explain what does this line of code do or why did we use it?

onRecipeSelectedInterface listener = (onRecipeSelectedInterface) getActivity();

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

We need to get a handle on the listener interface so we can call it when needed. Since the interface is implemented in the Activity, we use getActivity() to get a reference to it. However the value getActivity() returns is not of type onRecipeSelectedInterface. Its type is a general Activity, not the specific MainActivity (or whatever the activity class is named here) that implements onRecipeSelectedInterface. So we need to explicitly downcast it with the (onRecipeSelectedInterface) part to make the types match.