Un Ny Un Ny - 1 month ago 23
Android Question

Android Fragment lifecycle and FragmentManager.add()

I have MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, AFragment.newInstance(75))
.commit();
}

@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}


Also, I have AFragment

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);

view.findViewById(R.id.show_b_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();

appCompatActivity.getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, BFragment.newInstance())
.addToBackStack("B")
.commit();
}
});

return view;
}


BFragment is just an empty fragment.

And I have the following fragments lifecycle output:

Open the App:
A - onCreateView
A - onStart
A - onResume

Click R.id.show_b_btn on AFragment:
B - onStart
B - onResume

Click back button:
B - onPause
B - onStop

Close the App:
A - onPause
A - onStop


So, the question is why AFragment doesn't call onPause when I click ShowBFragment and why AFragment doesn't call onResume when I click back button?

I think it happens because I use .add() and BFragment just overlays AFragment, so AFragment also "lives" when BFragment is visible, am I right?

Answer

Just replace

getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, AFragment.newInstance(75))
                .commit();

with

getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, AFragment.newInstance(75))
                .commit();

This is what will happen if you use FragmentTransaction.add on a container. Your added fragment will be placed on top of your existing fragment. If you use FragmentTransaction.replace(R.id.container,fragment) it will remove any fragments that are already in the container and add your new one to the same container

you can also refer below link

Difference between add(), replace(), and addToBackStack()

Comments