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 Managing Fragments Initializing a Fragment with Data

findFragmentByTag() why did it return the ViewPagerFragment?

In the onCreate() method of MainActivty, we passed in the findFragmentByTag() the LIST_FRAGMENT tag. So why when we rotated the app (the onCreate() is called again) it restored the ViewPagerFragment but not the ListFragment ? Thanks!

1 Answer

Boban Talevski
Boban Talevski
24,793 Points

I assume you are referring to the case when we have opened a specific recipe and then we rotate the device. What I think happens is that Android automatically restores the fragment we are viewing, be it ListFragment or ViewPagerFragment (as in the assumed case) regardless of that line where we call findFragmentByTag().

That line is still there for the same reason it was added in the first place and that is to not create a duplicate ListFragment on each device rotation. I don't think It's there to ensure fragments are recreated. And since we are not creating a ViewPagerFragment in onCreate(), we don't need to check for that fragment to see if it was already created as it's not created "automatically", but on a tap/click on a recipe.

Both fragments seem to be kept in the backstack on device rotation (assuming we added them) so if you open a specific recipe, rotate the device, then click the back button, you'll be back to the list of recipes (ListFragment), which means rotation didn't change anything in the backstack, we can still go to the previous fragment after rotating the device. As far as I understand, everything (or most things) about restoring fragments seems to be done by Android automatically (except when it isn't :), but I guess that's not the case in this example).