我想在多个 Activity 中使用一个片段。
在我将在第一个 Activity 中使用它,我创建了它
final ScoreBoard fragment = new ScoreBoard();
getFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
在第二个 Activity 中,我在 onCreate() 方法中放置了相同的代码。
然而,即使我已经通过 onSavedInstanceState() 和 onActivityCreated() 保存了它们,片段也会不断重置并且不会将其值保留在第二个 Activity 中。我是在重新创建片段并重置它吗?谢谢你。
最佳答案
是的,您可以在不同的 Activity 中使用相同的片段。
在需要调用片段的所有 Activity 中创建一个 fragment_container View 。然后将片段调用到该容器中。
前任 :
Activity A: Activity A 中的调用片段
final ScoreBoard fragment = new ScoreBoard();
getFragmentManager()
.beginTransaction()
.add(R.id.fragment_container_activityA, fragment)
.commit();
Activity B: Activity B 中的调用片段
final ScoreBoard fragment = new ScoreBoard();
getFragmentManager()
.beginTransaction()
.add(R.id.fragment_container_activityB, fragment)
.commit();
关于android-fragments - android - 对多个 Activity 使用相同的片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42464251/