A blank page is displayed when you click a fragment again and replace with the same fragment

I have 3 fragments, Frag_A, Frag_B and Frag_C.

My navigation logic: Frag_A ==> Frag_B ==> Frag_C. First, Frag_A is added to the layout, so the first time Frag_A is displayed on the screen, and then, if the user clicks Next, Frag_A is replaced by Frag_B, now Frag_B is displayed on the screen, if the user clicks Next, Frag_B is replaced by Frag_C, so that Frag_C is displayed on the screen .

At the moment, everything is working fine with my code.

The way to change the following fragment:

//here, argument 'fragment' is either Frag_B or Frag_C public void showFragment(Fragment fragment){ FragmentManager fragMgr = activity.getSupportFragmentManager(); FragmentTransaction fragTrans = fragMgr.beginTransaction(); fragTrans.replace(R.id.frag_placeholder, fragment, fragmentName); fragTrans.addToBackStack(null); int transId = fragTrans.commit(); fragMgr.executePendingTransactions(); } 

Activity layout file (Frag_A is added to frag_placeholder when Activity starts):

 <?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <FrameLayout android:id="@+id/frag_placeholder" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </merge> 

But after displaying Frag_C, if I pop Frag_C, press the physical return button and call the showFragment(Frag_C) method to show Frag_C again right after my code finds that the physical button is pressed, I get a blank page shown on the screen. Why and how to fix it?

================= Explain ======================

I said above "* show Frag_C again right after my code finds that the physical button * is pressed *", this is what I mean:

In action:

 @Override public void onBackPressed() { super.onBackPressed(); //I detect the Physical Back button is pressed & invoke the method to show the popped Frag_C again. } 
+6
source share
1 answer

Based on a comment by @Luksprog, I found that if I create a new instance of Frag_C instead of always using the same instance, the problem with a blank page will be fixed.

+1
source

Source: https://habr.com/ru/post/945476/


All Articles