Search code examples
androidandroid-fragmentstabsandroid-lifecyclefragment-lifecycle

Lifecycle of tabs in Android


I am using a TabLayout and a ViewPager to implement 5 tabs as the detail view of a master/detail layout.

When I click on an item in the master view, it creates my detail view which in turn creates the necessary tabs. When the detail view is created, the onResume() method of the tabs are called. When I go back to my master view, the onPause() of the detail view is called, but the onPause() of the tabs are not called.

This is a problem as I subscribe to events in the onResume() method of each tab, but the unsubscription that is supposed to be done in onPause() of each tab never occurs.

So if I click n times on items in the master view, the subscription is done n times and each event is processed n times.

I tried this solution https://looksok.wordpress.com/2013/11/02/viewpager-with-detailed-fragment-lifecycle-onresumefragment-including-source-code/ that I found in an SO answer, but it didnt work as the id of the fragment in onFragmentPause() (Id 0) was not the same as the id of the fragment in onFragmentResume() (thus the subscription was null in onFragmentPause() ).

I don't understand how I can get the tab fragments to either not be duplicated every time an item is clicked, or how to make them call their onPause() method.


Solution

  • As specified in AndroidDev, one should call getChildFragmentManager() and not getSupportFragmentManager() when dealing with nested fragments.

    I was using the wrong method for my view pager adapter. I changed it to:

    adapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());