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 trialdlpuxdzztg
8,243 PointsAccessing a list in a fragment.
Hello.
I wanted to know if there is a way I could access a RecyclerView list, in an activity, from a fragment and then add items to that list.
Thank you.
1 Answer
Ben Deitch
Treehouse TeacherThe Android docs recommend using an interface: https://developer.android.com/training/basics/fragments/communicating.html
Also, while it's not a best practice, you could always make your list static :P
dlpuxdzztg
8,243 Pointsdlpuxdzztg
8,243 PointsHmm...okay. But what if I wan to select a specific button instead of an item in a list?
Ben Deitch
Treehouse TeacherBen Deitch
Treehouse TeacherYou should still be able to use an interface for that. You'd just put whatever action you want to take on that Button inside the Activity's implementation of the interface.
dlpuxdzztg
8,243 Pointsdlpuxdzztg
8,243 PointsAh okay, but how do I specify which button I want to press in my fragment?
Ben Deitch
Treehouse TeacherBen Deitch
Treehouse TeacherYou could create a different interface for each button or just have the interface function take in an argument to specify which button.
dlpuxdzztg
8,243 Pointsdlpuxdzztg
8,243 PointsQuick question actually. Should I create an interface for both my EditText's (because I wan't to send the data of the EditText's to the MainActivity) or should I create an interface for the button that sends you to the MainActivity?
Ben Deitch
Treehouse TeacherBen Deitch
Treehouse TeacherI'd probably do the Button. But if that doesn't feel right, try the EditTexts!
dlpuxdzztg
8,243 Pointsdlpuxdzztg
8,243 PointsOkay, thanks!
Also, one final question. I want the info I get from my fragment to display in another activity, should I implement the fragment in the fragment holder activity or the activity where I want the info to be displayed?
Ben Deitch
Treehouse TeacherBen Deitch
Treehouse TeacherI'd go with the Fragment holder Activity.