【发布时间】:2016-07-19 10:55:43
【问题描述】:
我已将 Fragment 添加到 Activity 之类的
getSupportFragmentManager().beginTransaction()
.add(R.id.container,new MyFragment).commit();
其中container 是FrameLayout 的id
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
现在我如何获得 Fragment in Activity like this
的实例从Fragment B 得到结果后,我必须调用Fragment A 的方法。
我在 Fragment B 中创建了一个接口,并在 Activity 中实现了它。现在我必须将结果传递给 Fragment A。我无法获取 Fragment A 的实例。
我不想做的一件事是在 Activity 中创建 Fragment A 的私有实例并调用它的方法。
【问题讨论】:
-
你可以将这个方法设为静态
-
为什么要获取 Fragment 实例?最好在 Activity 中创建一个接口并覆盖方法并从 Fragment 调用它。这样就可以将所有数据从 Fragment A 获取到您的 Activity
-
使用这个 getActivity().getSupportFragmentManager().beginTransaction() .add(R.id.container,new MyFragment).commit();
-
使用 FragmentTransaction 的 add(int containerViewId, Fragment fragment, String tag) 方法和 FragmentManager 的 findFragmentByTag(String) 方法。
标签: android android-fragments interface fragmentmanager android-framelayout