Nested fragment with wrong activity reference afte

2019-05-01 12:05发布

I'm finally looking into the new nested fragments APIs in the support library revision 11.

Everything It worked pretty well till I tried to use the activity reference held by the nested fragments. After a configuration change the childFragment doesn't seem to get detached and re-attached to the new activity.

Basically after an orientation change my childFragment is in an inconsistent state from which I can't get the correct activity instance with getActivity().

I manged to get the correct one using getParentFragment().getActivity() and it works, but I don't think that's the right way to go.

here is the code I use to add the fragment in the parentFragment the first time, after that the fragment is automatically added back to the parentFragment:

        public void addChildFragment() {
            Fragment f = getFragment().getChildFragmentManager().findFragmentByTag( FRAGMENT_CHILD_TAG );
            if (f == null) {
                FragmentTransaction ft = getFragment().getChildFragmentManager().beginTransaction();

                f = new TrackBrowserFragment();
                f.setArguments( getFragment().getArguments() );

                ft.add( R.id.fragment_album_detail_child_fragment_layout, f , FRAGMENT_CHILD_TAG );
                ft.commit();
            }
        }

This inconsistent in the activity instance obviously lead to multiple problem with my fragment ( binds with services, broadcast receivers and so on ). I'm probably doing something wrong cause I don't think that this is the correct behavior of a nested fragment.

so:

Am I doing something wrong with the code? Is this the expected behavior of a nested fragment?

Am I missing something? Should I detach/attach it by myself?

Thanks

1条回答
女痞
2楼-- · 2019-05-01 12:24

I found out wich was the problem, i was using setRetainInstance(true) in the parent fragment and that kept the child fragment to be detached.

After I Removed that line everything works as expected

查看更多
登录 后发表回答