ViewPager+Fragment引起的错误:No Activity

1.bug的log

java.lang.IllegalStateException: No activity

at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)

at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)

at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1861)

at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1474)

at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:931)

at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)

at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)

at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)

at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)

at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)

at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)

at android.support.v4.view.ViewPager.populate(ViewPager.java:880)

at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1374)


2.出现场景

第一次启动程序可以正常运行,随便切换tab也不会有问题,第二次必崩!


3.bug出现的原理及如何修复


This seems to be a bug in the newly added support for nested fragments. Basically, the child FragmentManager ends up with a broken internal state when it is detached from the activity. A short-term workaround that fixed it for me is to add the following to onDetach() of every Fragment which you call getChildFragmentManager() on:

@Override

public void onDetach() {

    super.onDetach();


    try {

        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");

        childFragmentManager.setAccessible(true);

        childFragmentManager.set(this, null);


    } catch (NoSuchFieldException e) {

        throw new RuntimeException(e);

    } catch (IllegalAccessException e) {

        throw new RuntimeException(e);

    }

}

4.是什么引起的bug

If you look at the implementation of Fragment, you'll see that when moving to the detached state, it'll reset its internal state. However, it doesn't reset mChildFragmentManager (this is a bug in the current version of the support library). This causes it to not reattach the child fragment manager when the Fragment is reattached, causing the exception you saw.


参考资料:http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed


你可能感兴趣的:(ViewPager+Fragment引起的错误:No Activity)