Search code examples
androidtabsoncreateondestroy

Android: onCreateView() runs from one tabs away


I am creating a tabbed app and I am running into a problem. onCreateView() runs when I click the tab next to where I am. What I mean is if I have three tabs (setup, maps, and motor) the onCreateView() view for maps and setup will run if I click on the motor tab. Also the onDestroyView() for motor will not run until I get two tabs away by clicking on setup. Is there anyway around this, and have them run when the specific tab is clicked or moved away from?


Solution

  • The reason this occurs is because you are using a ViewPager to display your tabbed content.

    The ViewPager is designed to preload content in (a minimum of one of) the tabs/fragments on either side of the current tab/fragment. This is the case because Android needs to preload this content in order to display it responsively when you change/swipe between tabs/fragments in your ViewPager.

    This cannot be disabled, as the minimum number of adjacent tabs you can set to be pre-loaded is 1 (meaning that the content in the tabs to the immediate left and right will always be pre-loaded when using a ViewPager).

    I suggest figuring out why this is a problem for your app (as in most cases it shouldn't be), and then deciding whether or not a ViewPager is appropriate for your particular application.. as the behavior you are describing is expected for a ViewPager.