在两个片段之间添加一个侦听器 [英] Adding a listener between two fragments
问题描述
我有两个片段,假设A和B,其中B包含一个列表.我想在片段B上添加一个侦听器,以通知片段A所选列表项.我不知道如何在片段B中初始化侦听器,因为在片段的构造函数中传递参数是一种不好的做法.
I have two fragments, A and B let's say, where B contains a list. I would like to add a listener on Fragment B that notifies Fragment A of the chosen list item. I couldn't figure out how to initialize the listener in Fragment B since it is bad practice to pass arguments in fragment's constructors.
注意:片段B包含在片段A内,即片段A中有一个FrameLayout;片段B涵盖了那个FrameLayout.
NOTE: Fragment B is contained inside Fragment A. i.e. I have a FrameLayout in Fragment A; and Fragment B covers that FrameLayout.
知道我该怎么做吗?
推荐答案
如果您说片段B是片段A的子片段(也就是说,您已使用片段A的getChildFragmentManager()
将其添加到片段A中),则可以使用与Activity
接口相同的方法,但是使用getParentFragment()
而不是getActivity()
.
If you're saying that Fragment B is a child fragment of Fragment A (that is, you've added it to Fragment A using Fragment A's getChildFragmentManager()
), then you can use the same approach that you use for Activity
interfaces, but using getParentFragment()
instead of getActivity()
.
例如:
片段B:
@Override
public void onAttach(Context context) {
MyInterface myInterface = (MyInterface) getParentFragment();
}
假定片段A实现了MyInterface
.
我们用来避免必须知道某个片段是由另一个片段还是由一个Activity托管的一种便捷方法是:
One convenience method we've used to avoid having to know whether a Fragment is hosted by another Fragment or an Activity is something like:
public static <T> getInterface(Class<T> interfaceClass, Fragment thisFragment) {
final Fragment parent = thisFragment.getParentFragment();
if (parent != null && interfaceClass.isAssignableFrom(parent)) {
return interfaceClass.cast(parent);
}
final Activity activity = thisFragment.getActivity();
if (activity != null && interfaceClass.isAssignableFrom(activity)) {
return interfaceClass.cast(activity);
}
return null;
}
然后您可以使用:
MyInterface myInterface = getInterface(MyInterface.class, this);
并且片段B是作为子片段还是直接在活动中托管都没有关系.
and it doesn't matter whether Fragment B is hosted as a child Fragment or in an Activity directly.
这篇关于在两个片段之间添加一个侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!