简体   繁体   English

在相同的布局中使用两次片段

[英]Use fragment twice in same layout

Is it possible to reuse a fragment twice in one layout? 是否可以在一个布局中重复使用两次片段? I have a layout of two tabs, Tab A and Tab B.. each tab displays a view that consists of a list (of type A or B) of items on the left and the details of the selected item on the right. 我有两个选项卡的布局,选项卡A和选项卡B ..每个选项卡显示一个视图,该视图由左侧项目列表(类型A或B)和右侧所选项目的详细信息组成。 The "detail view" (on the right pane) is the same for both types of lists, so I want to have it remain while the list is swapped out depending on what tab is selected. 对于这两种类型的列表,“详细视图”(在右侧窗格中)是相同的,因此我希望在列表被换出时保留它,具体取决于所选的选项卡。

I have tried to include the details fragment in layout XML for both tabs but get a runtime error about duplicates. 我试图在两个选项卡的布局XML中包含详细信息片段,但是获得有关重复项的运行时错误。 So then I tried to add them dynamically at runtime with a FragmentTransaction but get a similar error (fragment has already been added). 那么我尝试在运行时使用FragmentTransaction动态添加它们但是得到类似的错误(已经添加了片段)。

Is what i want to do possible? 我想做什么?

You should add the fragments dynamically setting different TAGs for each fragment and then finding them with getFragmentManager().findFragmentByTag("TAG"); 您应该添加的fragments动态设定不同TAGs每个片段,然后用发现它们getFragmentManager().findFragmentByTag("TAG"); In each TAB view you can add a FrameLayout and then use FragmentTransaction.replace function. 在每个TAB视图中,您可以添加FrameLayout ,然后使用FragmentTransaction.replace函数。

I had a similar problem (adding the same fragment many times in a ViewFlipper ) and solved it by using different tags. 我遇到了类似的问题(在ViewFlipper多次添加相同的fragment )并使用不同的标签解决了它。

You could create duplicate classes. 您可以创建重复的类。 One from the other. 一个来自另一个。 And rename the second class to another name. 并将第二个类重命名为另一个名称。

And set the second layout to 并将第二个布局设置为

  class="name of second class"

Then rename the wigdets for use in the second renamed class that is identical to the first except different widget id's. 然后重命名wigdets以在第二个重命名的类中使用,该类与第一个除了不同的小部件ID相同。

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

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