我试图更好地理解界面、 Activity 和 fragment 之间的相互作用。
根据this link from the Android documentation :
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
他们举了这个例子:
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
如果您正在处理嵌套的 fragment 链,情况会如何变化?
例如,假设我有一个 Activity,其中包含一个 Fragment,然后该 Fragment 包含另一个 Fragment,等等。明确地说:
Activity --> Fragment1 --> Fragment2 --> Fragment3 --> Fragment4 --> Fragment5
我试图了解执行以下操作的公认最佳实践:
假设 Fragment5 有一个 EditText 和一个附加了 OnClickListener 的 Button。我按下按钮,EditText 的内容以某种方式发送到 Fragment3 中的函数。
我的问题:
我假设我们需要在 Fragment5 中定义一个接口(interface)/监听器,就像上面的例子一样,这意味着前面的 Activity 方式应该实现该接口(interface),因为根据文档,Activity 应该在之间传递信息 fragment 。
但是现在,我们如何从这个 Activity 中将信息传递给 Fragment3?
最佳答案
该文档介绍了同级 fragment 到 fragment 的通信。他们应该通过家长 Activity 进行沟通。
对于子 fragment 到父 fragment 的通信,您可以直接通信。
((ParentFragment) getParentFragment ).doSomething();
你可以有一个接口(interface),让父fragment实现它。然后子fragment可以通过接口(interface)与父fragment通信,而不需要直接与另一个fragment通信。
关于java - 深度嵌套链中的 fragment 之间如何通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37018698/