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

Accessing 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
STAFF
Ben Deitch
Treehouse Teacher

The 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

Hmm...okay. But what if I wan to select a specific button instead of an item in a list?

Ben Deitch
Ben Deitch
Treehouse Teacher

You 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.

Ah okay, but how do I specify which button I want to press in my fragment?

Ben Deitch
Ben Deitch
Treehouse Teacher

You could create a different interface for each button or just have the interface function take in an argument to specify which button.

Quick 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
Ben Deitch
Treehouse Teacher

I'd probably do the Button. But if that doesn't feel right, try the EditTexts!

Okay, 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
Ben Deitch
Treehouse Teacher

I'd go with the Fragment holder Activity.