Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot setMaxLifecycle for Fragment not attached to FragmentManager: ViewPager

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;
}
like image 380
Anupriya Avatar asked Aug 06 '19 06:08

Anupriya


1 Answers

Try Handler().post { myPagerAdapter.removeFragment(..) }

If you are running this method for some reason on another thread, make sure to put Handler(Looper.getMainLooper()).post { ... } instead.

The problem is that you might be doing a transaction while the ViewPager itself is handling an animation or its own state saving. Doing the above allows us to completely run the ViewPager's state saving completely before doing a transaction.

I had the same problem, doing this fixed it for me.

Specifically, this is my code that I am running inside of onPageScrollStateChanged(..) (presumably you are doing the same)

        override fun onPageScrollStateChanged(state: Int) {
            if (upcomingPage == 0 && state == ViewPager.SCROLL_STATE_IDLE) {
                homePagerRoot?.post { vpAdapter.clearExtraFragments() }
            }
        }
like image 165
Daniel Kim Avatar answered Oct 19 '22 23:10

Daniel Kim