3

I have an app that uses fragments to display data. The main activity shown below controls the fragments with a recyclerview inside it and when I do an orientation change it I have, what looks like, one recyclerview overlapping another. On every orientation change, another fragment is being created. How would I fix this? Any help would be great

public class MainActivity extends AppCompatActivity
        implements NotesFragment.OnFragmentInteractionListener, EditFragment.SaveFragmentItem {

    EditFragment editFrag;
    NotesFragment notesFrag;

    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        notesFrag = new NotesFragment();
        editFrag = new EditFragment();

        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.container1, notesFrag);
        fragmentTransaction.commit();

    }

   ....
}
ChrisR
  • 607
  • 6
  • 16

1 Answers1

3

I figured out what was happening. This was the offending line of code:

    fragmentTransaction.add(R.id.container1, notesFrag);

I needed to use the replace() method, replacing the fragment after every orientation change, instead of adding another instance of the fragment to the FragmentManager. Simple answer, yet frustrating ;)

ChrisR
  • 607
  • 6
  • 16
  • you can also use the add function and add background color to your xml, so the previous layout wont show – Rashid Apr 19 '16 at 03:19