繁体   English   中英

从子片段更新父片段

[英]Updating Parent Fragment from Child Fragment

在我的 android 应用程序中,我有两个 Fragment。 父片段包含可用过滤器类型列表,当单击特定过滤器类型(在父片段 - 黄色背景中)时,相应的子片段(粉红色背景)会打开,其中包含所选过滤器类型的可用选项列表。 我的要求是一旦用户在子片段中选择/取消选择一个选项,它应该反映/更新父片段中的选项计数(绿色)。

请检查附加的线框。

在此处输入图片说明

您可以使用 Otto Bus 进行片段、片段活动、服务等之间的通信。

也许,第一次如果你之前没有使用过,你可能会有点奇怪,但它非常强大且非常易于使用。 您可以在此处找到库和教程:

http://square.github.io/otto/

一个例子。 在您的适配器或您的项目单击事件中,您可以通过总线发送一个对象。

在您的总线中,您调用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM