[英]Updating Parent Fragment from Child Fragment
您可以使用 Otto Bus 进行片段、片段活动、服务等之间的通信。
也许,第一次如果你之前没有使用过,你可能会有点奇怪,但它非常强大且非常易于使用。 您可以在此处找到库和教程:
一个例子。 在您的适配器或您的项目单击事件中,您可以通过总线发送一个对象。
在您的总线中,您调用 post 方法并传递对象。 (我建议为总线创建一个单例)。
单例总线提供程序。
/**
* Canal de comunicacion
*/
public class BusProvider {
private static final Bus REST_BUS = new Bus(ThreadEnforcer.ANY);
private static final Bus UI_BUS = new Bus();
private BusProvider() {};
public static Bus getRestBusInstance() {
return REST_BUS;
}
public static Bus getUIBusInstance () {
return UI_BUS;
}
}
您在总线中(在您的子片段中)发送一个对象,如下所示:
BusProvider.getUIBusInstance().post(itemSelected);
在你的父片段中你订阅了这个事件:
@Subscribe
public void activitySelected(final Item itemSelected) {
}
希望对你有帮助!!
即使我的回答可能会迟到,我想它仍然可以提供帮助:
解决方案很简单,如果您需要从子片段访问父片段,则在将其添加到堆栈时使用父片段的特定标记,如下面的代码示例所示:
1)在包含活动中:
// We instanciate the parent fragment
ParentFragment parentFragment = new ParentFragment();
FragmentTransaction ft = fm.beginTransaction();
// We add the parent fragment with a tag, so we can use it later to fetch
// the current instance of the parent fragment from the child fragment
ft.replace(R.id.content_frame, parentFragment, "parent_fragment_tag");
ft.addToBackStack(null);
// Commit transaction
ft.commit();
2)在子片段中,我们像这样获得当前的父片段实例:
Fragment parentFragment = getFragmentManager().findFragmentByTag("parent_fragment_tag");
我希望这个答案能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.