title: Fragments overlapping in Android
body: <p>I'm trying to switch between fragments without losing the previous contents, so I decided to implement this way to do it:</p>
  
  <pre><code>private void loadFragment(Fragment fragment) {
      FragmentManager fragmentManager = getSupportFragmentManager();
      fragmentManager.beginTransaction().hide(fragment);
      if (!alreadyOpened[currentIndex]) {
          alreadyOpened[currentIndex] = true;
          fragmentManager.beginTransaction().add(R.id.fragment_container,fragment).commit();
      } else {
          fragmentManager.beginTransaction().show(fragment).commit();
      }
  }
  </code></pre>
  
  <p>With this method I check if a fragment has been already opened: if yes, I show it, if not I add it. Then I declare it as "alreadyOpened". The problem is that when I switch between fragments I see all the three fragments overlapping. How can I solve it?
  This is the menu bar when I invoke the loadFragment method:</p>
  
  <pre><code>private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
          = new BottomNavigationView.OnNavigationItemSelectedListener() {
  
      @Override
      public boolean onNavigationItemSelected(@NonNull MenuItem item) {
          switch (item.getItemId()) {
              case R.id.bbn_item1:
                  currentIndex = 0;
                  loadFragment(new HomeFragment());
                  return true;
              case R.id.bbn_item2:
                  currentIndex = 1;
                  loadFragment(new PopularFragment());
                  return true;
              case R.id.bbn_item3:
                   currentIndex = 2;
                  loadFragment(new PlayingFragment());
                  return true;
          }
          return false;
      }
  };
  </code></pre>
  
  <p>EDIT: new code </p>
  
  <pre><code>List&lt;Fragment&gt; fragments = new ArrayList&lt;&gt;();
  
  private void loadFragment(Fragment fragment) {
      FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
      if (alreadyOpened[currentIndex]) {
          ft.replace(R.id.fragment_container, fragments.get(currentIndex));
      } else {
          fragments.add(currentIndex, fragment);
          alreadyOpened[currentIndex] = true;
          ft.replace(R.id.fragment_container, fragment);
      }
      ft.addToBackStack(null);
      ft.commit();
  }
  </code></pre>