FragmentStatePagerAdapter is deprecated from API 27

MJM picture MJM · Jul 2, 2018 · Viewed 37.7k times · Source

FragmentStatePagerAdapter is deprecated from API 27. What's the alternative of FragmentStatePagerAdapter?

private class MainPagerAdapter extends FragmentStatePagerAdapter {

    MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment result = new DummyFragment();
        return result;
    }

    @Override
    public int getCount() {
        return 5;
    }

}

Above code shows FragmentStatePagerAdapter, getItem(...) and super(...) as deprecated.

Answer

hkpogo picture hkpogo · May 23, 2019

Switch to ViewPager2 and use FragmentStateAdapter instead as mentioned by Erik Jhordan Rey.


Old answer (deprecated too now)

The following constructors do the same

super(@NonNull FragmentManager fm)
super(@NonNull FragmentManager fm, BEHAVIOR_SET_USER_VISIBLE_HINT)

Passing BEHAVIOR_SET_USER_VISIBLE_HINT got deprecated. You should pass BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT instead.

The difference in passing those is explained in FragmentPagerAdapter:

 /**
 * Indicates that Fragment#setUserVisibleHint(boolean) will be 
 * called when the current fragment changes.
 */
@Deprecated
public static final int BEHAVIOR_SET_USER_VISIBLE_HINT = 0;

/**
 * Indicates that only the current fragment will be 
 * in the Lifecycle.State#RESUMED state. All other Fragments 
 * are capped at Lifecycle.State#STARTED.
 */
public static final int BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT = 1;