Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 524
MJM Avatar asked Jul 02 '18 07:07

MJM


People also ask

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

FragmentPagerAdapter is used exactly like FragmentStatePagerAdapter . It only differs in how it unloads your fragments when they are no longer needed (Figure 11.4). With FragmentStatePagerAdapter , your unneeded fragment is destroyed.

What can I use instead of FragmentPagerAdapter?

FragmentStateAdapter instead. Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

How do I refresh FragmentStateAdapter?

You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.

What is Behavior_resume_only_current_fragment?

FragmentStatePagerAdapter(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT). BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, it means offset fragments will be executed on onStart() and the current fragment will be executed onStart() and onResume().


1 Answers

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; 
like image 124
eytschkay Avatar answered Sep 24 '22 13:09

eytschkay