Java – Use the same fragment multiple times in the same activity/layout

Use the same fragment multiple times in the same activity/layout… here is a solution to the problem.

Use the same fragment multiple times in the same activity/layout

Not 100% aware of the terminology, so be patient.

I have an activity that compares two projects side by side, one on the left and the other on the right. The projects contain the same layout, so I was wondering if I could reuse the fragment java and XML file on the left and instantiate a new instance. I might just copy and paste the fragment file on the left into the same file on the right, but I feel as if there has to be a more elegant way.

TDLR: Is there a way to have two or more instances of the same fragment run in the same layout/activity?

Solution

You need to make a parent layout (such as a frame layout or a direct fragment) using 2 side-by-side containers.

If you prefer to be in code, you can add fragments to these containers through FragmentManager transactions.

getSupportFragmentManager()
     .beginTransaction().add(R.id.left_container,new YourFragment(),"some tag1").commit();

getSupportFragmentManager()
     .beginTransaction().add(R.id.right_container,new YourFragment(),"some tag2").commit();

Related Problems and Solutions