This question has already been answered:

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layoutForFragment = (FrameLayout) findViewById(R.id.layout_for_fragment); fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.layout_for_fragment,cardStation); fragmentTransaction.commit(); } 

In the OnCreate method, I insert the fragment in FrameLayout. The problem is that when you rotate the screen or when you fly out with an error, the fragments overlap each other in the same place. How to solve a problem ?

Reported as a duplicate by Vladyslav Matviienko , aleksandr barakin , cheops , user194374, Nick Volynkin Jul 12 '16 at 6:59 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • five
    Possible duplicate question: Overlay fragment on a fragment. The previous fragment is visible behind the added fragment . The missed answer is correct. - pavlofff
  • @pavlofff, here is another thing - there was an extra operation in the goal of the take, but it simply doesn’t check if the fragment has already been added - YuriySPb
  • @YuriSPb yes, you are right. - pavlofff
  • Still as an option to use .replace instead of .add - doomsilka
  • Yes, the fragment will not be layered on the previous one, but it will be added once again, replacing the one that is already in memory of the FragmentManager, so - YuriySPb

1 answer 1

  1. When you rotate the screen, the activation is recreated.
  2. When recreating the activation system tries to restore the previous state.
  3. In the previous state, a fragment was added to the activation and the system restores it by adding it to the screen.
  4. After this, onCreate is executed, where you add another fragment. Total you have (the number of turns of the screen) * 1

You just need to check whether the active fragment has restored the fragment by searching it in the FragmentManager by the container ID, and if not, add it:

 cardStation = getSupportFragmentManager().findFragmentById(R.id.layout_for_fragment); if (cardStation == null) { cardStation = new CardStation(); getSupportFragmentManager(). beginTransaction().add(R.id.layout_for_fragment, cardStation) .commit(); } 
  • There is another way (at the very end of the page) to check if the fragment is added if (savedInstanceState == null) - the first time the activation is started, the saved state is null, it is initialized by the system when turning, even if the programmer did not save anything there. It is much "cheaper" to search for fragments in the ID fragment manager. - pavlofff
  • @pavlofff, yes, this is also possible, but if the fragment is not full screen, but only partly added and not always, but by event, then this will not help) - YuriiSPb