Search code examples
androidandroid-fragmentsretain

Android retain fragments on ViewPager


in my activity i have ViewPager which that implemented for two fragments, in these fragments i have some popup such as dialog which on rotate device popups start again, this popups is on createview and after running parent activity i get some data from server, how can i retain these fragments not to load again on change device orientation ?

Activity:

private void setupViewPager(ViewPager viewPager) {
    adapter = new RegisterViewPagerAdapter(getSupportFragmentManager());

    //adapter.addFragment(new FragmentEmpty());
    adapter.addFragment(FragmentCheckValidationCode.getInstance());
    adapter.addFragment(FragmentRegisterPhoneNumber.getInstance());

    viewPager.setOffscreenPageLimit(1);
    viewPager.setAdapter(adapter);
    registerPages.setCurrentItem(1);
    registerPages.setPageMargin(50);
    registerPages.setScrollDurationFactor(5);
}

fragments:

public static FragmentCheckValidationCode getInstance() {
    if (instance == null) {
        instance = new FragmentCheckValidationCode();
    }
    return instance;
}

FragmentCheckValidationCode:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //@formatter:off
        activity                  = getActivity();
        context                   = getActivity().getBaseContext();
    //@formatter:on

    setRetainInstance(true);
}

Solution

  • if you don't use a different layout for the landscape mode you could add the tag

    android:configChanges="orientation|screenSize|keyboardHidden"
    

    to your Activity in your Manifest. This tells the system that you handle the configuration change by yourself.