Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifecycle of a replaced ViewPager and BackStack?

I'm really messed up with the android ViewPager's lifecycle, and I'm starting to think that there something wrong in the structure of my app. So I would like a confirmation if I can do the following :

  • I have an application showing some tabs. One of those tab is showing a ViewPager, in which there is two ListFragments. Those ListFragments are create in the onCreate event of the ViewPager.
  • When you click an item in one of the ListFragments, it is replacing the entire ViewPagerFragment by a different fragment (which is another a ListFrament).

Here is the code that I use to replace the ViewPager with the new ListFragment

FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

ft.replace(R.id.container, new RequestForm(requestsList.get(itemIndex)));
ft.addToBackStack(null);
ft.commit();

From there, everything is working fine. But, if the user clicks the back button, I get the following situation:

  • ViewPager is reloading fine (from onCreateView), but the ListFragment inside won't show up. Look like my ListFragment's object are still alive, but it seems they lost their view, and onCreateView is not called to recreate it (because the object didn't slept while ViewPager was out).

I'm not posting more code here for now, because my intention is to know if what I'm trying to do is ok or not in an Android way of thinking. Will I have to fight against Android SDK to archive what I want to do?

like image 367
NLemay Avatar asked Mar 12 '13 19:03

NLemay


Video Answer


1 Answers

Well, as you can see, I'm not an Android User (I know much more about UI on iOS). This is why I was confuse.

After looking a different applications, I found out that Gmail and Google Play do have navigation that looks a little bit like mine (replacing a ViewPager by a new fragment, without creating a new activity).

And for my problem, it wasn't a structure problem. When you create the FragmentStatePagerAdapter, be sure to use getChildFragmentManager() and not getFragmentManager()!

ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
like image 88
NLemay Avatar answered Oct 16 '22 00:10

NLemay