2016-04-25 52 views
1

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

请检查附加的线框。

enter image description here

回答

1

可以使用奥托总线的片段之间晖,交通运输,碎片活动,服务等

也许,你第一次可以是一个有点怪异,如果你以前没有,但它使用非常强大且非常易于使用。你可以找到图书馆,这里的教程:

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

一个例子。在您的适配器或您有物品点击事件的地方,您可以通过总线发送一个对象。

在你的巴士你invoque 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) { 

} 

希望它帮助你!

+0

谢谢巴士是沟通的好方法。但是,一旦我在ParentFragment上收到事件,就无法更新FilterCount,因为Filter count是ListView的一部分。 – Alex

0

即使我的回答可能是晚了,我猜它仍然可以帮助:

解决方法很简单,如果你需要从一个孩子一个访问父片段,然后用一个特定的标记父

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"); 

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