How to extends FragmentPagerAdapter class?

909 views Asked by At

When I try to extend their class, the FragmentPagerAdapter is deprecated in my Android Studio page code. The problem is very annoying. I have searched a lot but have not found any results. Please have a look on the page below

package com.example.buyown;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

public class PageAdapter  extends FragmentPagerAdapter {

int tabCount;
public PageAdapter(@NonNull FragmentManager fm, int behavior) {
    super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT );
    tabCount= behavior;
}

@NonNull
@Override
public Fragment getItem(int position) {

    switch (position){
        case 0:return new buyOwnTab1();
        case 1:return new buyOwnTab2();
        default: return null;
    }


}

@Override
public int getCount() {
    return tabCount;
}
}
1

There are 1 answers

4
EpicPandaForce On

The documentation at https://developer.android.com/reference/androidx/fragment/app/FragmentPagerAdapter says:

This class is deprecated.

Switch to ViewPager2 and use FragmentStateAdapter instead.

Although technically, based on the internals of FragmentPagerAdapter versus FragmentStateAdapter, FragmentPagerAdapter is simple to follow as it relies on findFragmentByTag + attach + detach + add, while FragmentStateAdapter and ViewPager2 relies on a RecyclerView and "periodically executed gcFragments() calls" which is significantly trickier, so unless you explicitly require the new behaviors supported by ViewPager2, there is no reason to switch from ViewPager - as standard ViewPager also relies on standard mechanisms supported by Fragments.

That's why @SuppressWarnings("deprecation") is also a valid solution sometimes, although not always.

IIRC, the major key difference is simpler vertical swipe support, and better RTL support.