The fragment that is not the largest in the backstack resumes.

Given that the application flow is shown in graphical and textual form, described below.

Application flow

  • Fragment 1 is the bottommost fragment, but not in the backstack, by setting disallowAddToBackStack.
  • Fragment 2 is pushed onto the stack using fragmentTransaction.addToBackStack().
  • A new instance of fragment 1 is pushed onto the stack.
  • The topmost fragment (fragment 1) is unloaded from the stack.
  • Action 2 becomes the foreground.
  • Action 1 becomes the foreground.

Here is a generic method that I use to process fragments:

private void changeContainerViewTo(int containerViewId,  Fragment fragment, 
                                   Activity activity, String backStackTag) {

    if (fragmentIsAlreadyPresent(containerViewId, fragment, activity)) { return; }
    final FragmentTransaction fragmentTransaction = 
                 activity.getFragmentManager().beginTransaction();
    fragmentTransaction.replace(containerViewId, fragment);
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    if (backStackTag == null) {
        fragmentTransaction.disallowAddToBackStack();
    } else {
        fragmentTransaction.addToBackStack(backStackTag);
    }
    fragmentTransaction.commit();
}

Problem

When action 1 resumes at the last stage, the youngest instance of fragment 1 also resumes. At this point in time, fragment 1 returns nullto getActivity().

Question

  • , , ?
  • - ?
+5
3

Activity , , , FragmentManager , .

:

, (, ), , .

Activity onSaveInstanceState onRestoreInstanceState Fragment, :

public void onSaveInstanceState(Bundle outState){
    getFragmentManager().putFragment(outState,"myfragment", myfragment);
}
public void onRetoreInstanceState(Bundle inState){
    myFragment = getFragmentManager().getFragment(inState, "myfragment");
}

!: -)

+2

, , ( , ) , fragmentTransaction.addToBackStack(): , backstack, .

:

addToBackStack(), , , "".

, 2 :

fragmentTransaction.replace(containerViewId, fragment2);
fragmentTransaction.addToBackStack();
fragmentTransaction.commit();

3:

fragmentTransaction.disallowAddToBackStack()//or just no call to addToBackStack - you do not say
fragmentTransaction.replace(containerViewId, newfragment1);
fragmentTransaction.commit();

Fragment2 , backstack Fragment1. 4 , , 1 .

, , . , , , , .

+1

Android- , . , , Activity 2 Activity 1. , . , , , 1, 2.

Regarding the processing of individual fragments, you should take a look at this page . Its essence is that you should use getActivity only in certain functions of the fragment (based on the life cycle of the fragment ). This may mean that you need to move part of your logic to other functions.

+1
source

All Articles