简体   繁体   English

在相同的活动/布局中多次使用相同的片段

[英]Use same fragment multiple times in same activity/layout

Not 100% on terminology so bear with me. 不是100%的术语所以请耐心等待。

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. 这些项目包含相同的布局,所以我想知道是否可以重用左片段java和XML文件并实例化一个新实例。 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? tdlr:有没有办法让同一个片段的两个或多个实例在同一个布局/活动中运行?

You need to make a parent layout with 2 side-by-side containers (framelayout, for example or fragments directly). 您需要使用2个并排容器(例如framelayout或直接片段)创建父布局。

If you prefer in code, then add the fragments through FragmentManager transation in those containers. 如果您更喜欢代码,则通过FragmentManager转换在这些容器中添加片段。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM