Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use same fragment multiple times in same activity/layout

Not 100% on terminology so bear with me.

I have an activity that compares two items side by side, one on the left and another on the right. The items contain the same layout so I was wondering if I could reuse the left fragment java and XML file and instantiate a new instance. It is possible that I just copy and paste the left fragment files into identical files for right side but I feel as though there must be a more elegant method.

tdlr: Is there a way to make two or more instances of the same fragment operating in the same layout/activity?

like image 411
chiangy77 Avatar asked Jan 06 '23 23:01

chiangy77


1 Answers

You need to make a parent layout with 2 side-by-side containers (framelayout, for example or fragments directly).

If you prefer in code, then add the fragments through FragmentManager transation in those containers.

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

    getSupportFragmentManager()
     .beginTransaction().add(R.id.right_container,new YourFragment(),"some tag2").commit();
like image 85
aelimill Avatar answered Jan 19 '23 04:01

aelimill