FragmentStatePagerAdapter is deprecated from API 27

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.


Switch to ViewPager2 and use FragmentStateAdapter instead.

From there you can use onPause and onResume callbacks to determine which fragment is currently visible for the user. onResume is called when a fragment became visible and onPause when it stops to be visible. -> read more

Based on the comments of Eric and Reejesh.


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;

You may extend

androidx.fragment.app.FragmentStatePagerAdapter;

and call

super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

in your class's constructor


This works for me.

In Kotlin :

class TasksPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT )

You need to add behavior in your MainPagerAdapter like this:

super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);


The constructor with only FragmentManager as a paramaeter is duplicated and changed to

public FragmentStatePagerAdapter(@NonNull FragmentManager fm,
        @Behavior int behavior)

but you can achieve the same by using the below constructor, you should also inject your tabsNumber via constructor to avoid using hard codded numbers, and return it via getCount().

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    this.numberOfTabs= NumOfTabs;
}

@Override
    public int getCount() {

        return numberOfTabs;
    }

for more details check the official documentation for AndroidX