2016-04-25 54 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"); 

我希望這個答案可以有所幫助。