相关文章推荐
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

FragmentPagerAdapter class is deprecated

Since API 27 FragmentPagerAdapter is deprecated. What's the best alternative to use for this?

How to solve FragmentPagerAdapter issue.

  • Follow my code you easily solve this problem.
  • imports :

    import androidx.fragment.app.FragmentManager
    import androidx.fragment.app.FragmentPagerAdapter
    

    My Old Code :

    public class PagerAdapter extends FragmentPagerAdapter {
      public PagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
    int tab_count;
    public PagerAdapter(@NonNull FragmentManager fm, int behavior) {
        super(fm, behavior);
        tab_count=behavior;
    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position)
            case 0 : return new Ftab1();
            case 1 : return new ftab2();
            case 2 : return new Ftab3();
            default: return null;
    @Override
    public int getCount() {
        return tab_count;
    

    My New Code :

  • Follow my code you easily solve this problem. Note:

  • Replace FragmentPagerAdapter with FragmentStateAdapter

  • Create string of your fragment name

  • In XML & JAVA File,Replace ViewPager with ViewPager2.

     public class PagerAdapter extends FragmentStateAdapter {
     String[] fragment_names = new String[]{"chat","status","call"};
     public PagerAdapter(@NonNull FragmentActivity fragmentActivity) {
         super(fragmentActivity);
     @NonNull
     @Override
     public Fragment createFragment(int position) {
         switch (position)
             case 0 : return new Ftab1();
             case 1 : return new ftab2();
             case 2 : return new Ftab3();
             default: return null;
     @Override
     public int getItemCount() {
         return fragment_names.length;
                    I’m voting to close this question because this seems to be a combined question/answer, but should be split into a question and separate answer.
    – Ryan M - Regenerate response
                    Feb 25, 2022 at 22:54
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

  •  
    推荐文章