K
K
kirawa2018-03-13 10:52:03
Android
kirawa, 2018-03-13 10:52:03

How to set target fragment in item ViewPager?

Hello. I have a problem with android oreo. There is an item view pager in which the following code is called on click:

private void startNewOrderDoc() {
        ClientViewPagerContainer fragment  = new ClientViewPagerContainer();
        fragment.setTargetFragment(this, IDD_NEW_ORDER);
        FragmentTransaction fragmentTransaction;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            fragmentTransaction = getActivity().getFragmentManager().beginTransaction();
        } else{
            fragmentTransaction = getChildFragmentManager().beginTransaction();
        }
        fragmentTransaction.addToBackStack(null).replace(R.id.contentMain, fragment).commit();
    }

The program crashes with this error:
java.lang.IllegalStateException: Fragment ClientViewPagerContainer{a47f4aa #4 id=0x7f090067} declared target fragment JournalFragment{8d871c #4 id=0x7f09024c} that does not belong to this FragmentManager!
If we remove fragment.setTargetFragment(this, IDD_NEW_ORDER); that works.
Tell me what is the problem and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-03-13
@zagayevskiy

The problem is that
1) it is not necessary to use fragments from the platform (android.app.Fragment). It is necessary to use from support .
2) in the else branch, where getChildFragmentManager. If you look at the implementation of this method, it becomes clear that a new manager fragment is created inside it, which, of course, does not contain the this fragment.
When such a transaction is committed, the fragment manager checks to see if the target fragment is in the same manager as the one to whom it was exposed. Not located. And falls.
It's easy to fix. Those fragments that are in the child fragment manager'e can access the parent'u (in this case - this) through getParentFragment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question