Search code examples
androidandroid-fragmentsandroid-actionbaractivity

ActionBarActivity's lifecycle explanation


Let's say we have an application which consists of:

  1. ActionBarActivity called MainActivity with ViewPager as its layout (for horizontal swiping between fragments) which contains two fragments detailed below.
  2. SettingFragment which controls the visibility of the ContentFragment's Controls (e.g. when we choose 2 from the visibilitySpinner in Setting Fragment, it will make EditText1 and EditText2 on ContentFragment visible, while leaving EditText3 visibility as GONE), SettingFragment positioned on the first page of ViewPager.
  3. ContentFragment consists of 3 EditText.

So when the activity first created, will it create the fragments in order? (SettingFragment > ContentFragment) or will they be created at the same time? And to be more precise what is the best event to update the Visibility of Controls in ContentFragment?

What i have in mind is to create a button in SettingFragment then update the visibility of ContentFragment's control on the onClick event. This works fine but i think i will get NullPointerException if i try to use the same approach to update the visibility of multiple fragments at once (since AFAIK ViewPager only create previous and next page of our current "active" fragments, CMIIW).

Can anyone give me a clearer insight about this? Thank you very much.


Solution

  • ViewPager wasn't really designed to have interaction between pages. It was designed to cache and perform well while displaying rather unchanging content. Having said that, there are some workarounds that involve reloading the fragment every time the user changes the page, take a look at:

    Update data in ListFragment as part of ViewPager

    On the other hand, answering your question about the ViewPager only keeping previous and next fragments as active, you can control that like so:

    mViewPager.setOffscreenPageLimit(2);
    

    Reference: Prevent ViewPager from destroying off-screen views