I have tried with so many given examples but nothing worked for me. When I am trying to remove a page dynamically from viewPager then I am getting exception:
Cannot setMaxLifecycle for Fragment not attached to FragmentManager
My PagerAdapter is given below:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private final Context mContext;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
long baseId = 0;
public MyPagerAdapter(Context context, FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title, int position) {
mFragmentList.add(position, fragment);
mFragmentTitleList.add(position, title);
}
public void removeFragment(int position) {
mFragmentList.remove(position);
mFragmentTitleList.remove(position);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And to remove page I am calling method like
myPagerAdapter.removeFragment(viewPager.getCurrentItem());
I have tried with below given method too, but still getting exception
@Override
public int getItemPosition (Object object) {
int index = mFragmentList.indexOf (object);
if (index == -1)
return POSITION_NONE;
else
return index;
}