I have migrated ViewPager
to ViewPager2
and adapter FragmentPageAdapter
to FragmentStateAdaper
. In FragmentPageAdapter
there is a method called getItemPostion(Object obj)
by using this method I can able to replace fragments. In FragmentStateAdaper
class that method is not there how to replace fragments in viewpager2 with FragmentStateAdaper
.
Here my adapter:
public class BottomNavigationIcon extends FragmentStateAdapter implements FragChangeListner {
FragmentManager fm;
Fragment tmp;
public BottomNavigationIcon(@NonNull FragmentManager fragment, Lifecycle lc) {
super(fragment,lc);
this.fm=fragment;
}
@NonNull
@Override
public Fragment createFragment(int position) {
if (position == 1)
return SessionFragment.getInstance();
if (position == 2)
return OthersFragment.newInstance();
if (position == 3) {
if (tmp == null)
tmp = SettingsFragment.newInstance();
return tmp;
}
return ProcessFragment.newInstance();
}
@Override
public int getItemCount() {
return 4;
}
@Override
public void replaceFrag() { //here replacing fragment which is not working
fm.beginTransaction().remove(tmp).commit();
tmp = AboutFragment.newInstance();
notifyDataSetChanged();
}
}
and in my settings fragment i am just calling replaceFrag()
v.findViewById(R.id.about_me).setOnClickListener(v1 -> {
interface.replaceFrag();
});
Before migrate my adpter is somthing like below:
public class MyAdapter extends FragmentPagerAdapter implements FragChangeListner
{
private final FragmentManager mFragmentManager;
private Fragment tmp;
public MyAdapter(FragmentManager fm)
{
super(fm);
mFragmentManager = fm;
}
@Override
public Fragment getItem(int position)
{
if (position == 1)
return SessionFragment.getInstance();
if (position == 2)
return OthersFragment.newInstance();
if (position == 3) {
if (tmp == null)
tmp = SettingsFragment.newInstance();
return tmp;
}
return ProcessFragment.newInstance();
}
@Override
public int getCount()
{
return 4;
}
@Override
public int getItemPosition(Object object)
{
if (object instanceof SettingsFragment && tmp instanceof AboutFragment)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
@Override
public void replaceFrag()
{ //here replacing fragment which is working
mFragmentManager.beginTransaction().remove(tmp).commit();
tmp = AboutFragment.newInstance();
notifyDataSetChanged();
}
}
}
And my interface is
public interface FragChangeListner()
{
void replaceFrag();
}
is there any different way which i can replace the fragment in viewpager2 with FragmentStateAdapter adpter
2
Answers
You have to override
createFragment(position: Int)
method inFragmentStateAdapter
which returnsFragment
for respective positions.createFragment
can be override like thisApart from this, you also have to override
getItemCount()
inFragmentStateAdapter
, where you have to return total number of fragments.in your activity set viewpager
view pager adapter