Can't retain nested fragments

后端 未结 4 479
星月不相逢
星月不相逢 2020-12-24 08:42

Is there another way of saving the state of the nested fragment ? Or if we shouldn\'t do this, why ? Thanks !

02-13 11:42:43.258: E/AndroidRuntime(7167): ja         


        
4条回答
  •  生来不讨喜
    2020-12-24 09:20

    Problem: mChildFrgamentManager is being recreated (https://code.google.com/p/android/issues/detail?id=74222)
    Workaround: Retaining mChildFrgamentManager if fragment has setRetainInstance(true):

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        if (getRetainInstance()) {
            if (mRetainedChildFragmentManager != null) {
                try {
                    Field childFMField = Fragment.class.getDeclaredField("mChildFragmentManager");
                    childFMField.setAccessible(true);
                    childFMField.set(this, mRetainedChildFragmentManager);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } else {
                mRetainedChildFragmentManager = getChildFragmentManager();
            }
        }
    }
    

    Warning: With this code, setRetainInstace should be called before onAttach.

    P.S: This is a bit improved version of @attels answer.

提交回复
热议问题