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 trialvicente lee
6,271 PointsWhy do we need an interface?
I'm still a bit confused as to why we need an interface when implementing an onClickListener to a fragment? Can somebody explain this to me in the simplest way? Why can't we just have an onClickListener on the fragment itself and not go through the troubel of an interface?
1 Answer
Seth Kroger
56,414 PointsIn Model-View-Controller terms, the Activity is the Controller of the Fragments. The Activity is responsible for choosing which Fragment to display where, while the Fragment is responsible for what's inside itself. This way they keep their responsibilities separate. For the Activity to know it has to replace one Fragment with another, it has to have a callback implemented to do so.
Interfaces help with reusing Fragments. If we directly change to a new Fragment in the Fragment itself, we're hard-coding it to work directly with one particular Activity class and one particular new Fragment class. Using an interface means we don't have to code what specific actions to take. We simply send a message that an item was clicked and let the callback handle the details. Then any Activity that implements that interface will be able to use that Fragment instead of just one. (This is called loose-coupling vs. tight-coupling.)
vicente lee
6,271 Pointsvicente lee
6,271 PointsThanks! Very clear explanation.
Sammie Carswell
689 PointsSammie Carswell
689 PointsThis made a little more sense. But I'm still not quite grasping the concept of callbacks. I really need a good resource here. This seems to be a very important bit of info in order to truly understand what is happening here.