causing a java.IllegalStateException error, No Activity, only when navigating to Fragment for the SECOND time

前端 未结 8 1316
感动是毒
感动是毒 2020-12-08 06:39

I am getting a very puzzling bug that I have no idea how to even begin working through.

I have a simple app with one activity, the views are implemented with Fragme

8条回答
  •  生来不讨喜
    2020-12-08 07:26

    sadly, it's a bug of support v4, still there :(

    When you choose other Fragment via Navigation Drawer or other thing like it, the fragment which has sub-fragments is detached. So those sub-fragments' fragmentManager(getChildFragmentManager()) is no longer exist. while those fragments return, error occurred. Bomb!

    Obviously, support v4 should clean mChildFragmentManager in onDetach(), but it didn't, so we must depend on ourselves. such as following codes in the fragment which has sub-fragments:

    @Override
        public void onDetach() {
            try {
                Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            super.onDetach();
        }
    

    Everything will be OK, have a good day :)

提交回复
热议问题