Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
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!
Boban Talevski24,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).