title: Loading Fragment UI on-demand
body: <p><strong>Problem:</strong></p>
  
  <p>I am currently running into a problem where my app is trying to load too many fragments when it opens for the first time.</p>
  
  <p>I have <code>BottomNavigationView</code> with <code>ViewPager</code> that loads 4 fragments - each one of the <code>Fragment</code> contains <code>TabLayout</code> with <code>ViewPager</code> to load <strong>at least</strong> 2 more fragments.</p>
  
  <p>As you can imagine, that is a lot of UI rendering (10+ fragments) - especially when some of these fragments contain heavy components such as calendar, bar graphs, etc.</p>
  
  <p><strong>Currently proposed solution:</strong></p>
  
  <p>Control the UI loading when the fragment is required - so until the user goes to that fragment for the first time, there is no reason to load it.</p>
  
  <p>It seems like it's definitely possible as many apps, including the Play Store, are doing it. Please see the example <a href="https://drive.google.com/file/d/1mmtpTre7po9ImO91vPXexv1dxps2yF9L/view?usp=sharing" rel="noreferrer">here</a></p>
  
  <p>In the video example above - the UI component(s) are being loaded AFTER the navigation to the tab is completed. It even has an embedded loading symbol.</p>
  
  <p>1) I am trying to figure out how to do exactly that - at what point would I know that this fragment UI need to be created vs it already is created?</p>
  
  <p>2) Also, what is the fragment lifecycle callback where I would start the UI create process? <code>onResume()</code> means UI is visible to the user so loading the UI there will be laggy and delayed.</p>
  
  <p>Hope this is clear enough.</p>
  
  <hr>
  
  <p><strong>EDIT:</strong><br>
  I'm already using the <code>FragmentStatePagerAdapter</code> as <code>ViewPager</code> adapter. I noticed that the <code>super(fm)</code> method in the constructor is deprecated now:</p>
  
  <pre><code>ViewPagerAdapter(FragmentManager fm) {
      super(fm); // this is deprecated
  }
  </code></pre>
  
  <p>So I changed that to:</p>
  
  <pre><code>ViewPagerAdapter(FragmentManager fm) {
      super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
  }
  </code></pre>
  
  <p><code>BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT</code>: Indicates that only the current fragment will be in the Lifecycle.State.RESUMED state. All other Fragments are capped at Lifecycle.State.STARTED.</p>
  
  <p>This seems useful as the <code>onResume()</code> of the <code>Fragment</code> will only be called when the <code>Fragment</code> is visible to the user. Can I use this indication somehow to load the UI then?</p>