Android 从子片段更新父片段

Android 从子片段更新父片段,android,android-layout,android-fragments,Android,Android Layout,Android Fragments,在我的android应用程序中,我有两个片段。父片段包含可用筛选器类型的列表,当单击特定筛选器类型时(在父片段-黄色背景中),相应的子片段(粉色背景)将打开,并显示所选筛选器类型的可用选项列表。我的要求是,一旦用户在子片段中选择/取消选择一个选项,它应该反映/更新父片段中的选项计数(绿色) 请检查所附的线框 您可以使用Otto总线在片段、片段活动、服务等之间进行通信 也许,第一次你可能会有点奇怪,如果你以前没有使用过,但它是非常强大的,非常容易使用。您可以在此处找到库和教程: 举个例子。在适配

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

请检查所附的线框


您可以使用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");

我希望这个答案能有所帮助。

谢谢,公共汽车是一种很好的交流方式。但一旦收到ParentFragment上的事件,就无法更新FilterCount,因为FilterCount是ListView的一部分。