2013-01-24 98 views
0

這裏我們再次去。 我在寫一個使用片段的應用程序。 Stefan de Bruijn建議這比使用棄用的TabHost更好,他是對的,謝謝Stefan。多片段活動溝通

我終於得到了從一個片段到我的溝通活動工作得益於其他成員的幫助(你知道你是誰,謝謝大家)。

我現在有什麼希望是最後一個問題。我的應用程序在頂部是TextBox,它是Activity的一部分,左邊是一個永久ListFragment,右邊是FrameLayout,用於顯示不同的片段。

如果你喜歡在Activity中所有不同的碎片可以與之通話,是否有任何方法可以創建通用的「偵聽器」?

要獲得一個片段傳遞數據我已經使用了以下內容。

MainActivity

import com.example.fragger.CoreFragment.OnDataPass; 

import android.os.Bundle; 
import android.app.Activity; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.EditText; 

public class MainActivity extends Activity implements OnDataPass { 

和片段代碼: -

package com.example.fragger; 


import android.app.Activity; 
import android.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.os.Bundle; 
import android.widget.Button; 
import android.widget.RelativeLayout; 
import android.view.View.OnClickListener; 


public class CoreFragment extends Fragment{ 

int index; 
Button Button1,Button2,Button3; 
String Str,data; 
OnDataPass dataPasser; 

@Override 
public void onAttach(Activity a) { 
    super.onAttach(a); 
     dataPasser = (OnDataPass) a; 
} 


public static CoreFragment newInstance(int index) { 
    CoreFragment coreFragment = new CoreFragment(); 
    coreFragment.index = index; 
    return coreFragment; 
} 


public interface OnDataPass { 
    public void onDataPass(String data); 

} 

這是一個好主意,直​​到我告訴我的框架(例如PlaceFragment)不同的片段。由於onDataPass是從CoreFragment導入並實現的,因此我無法將其與其他任何東西一起使用。

有沒有辦法解決這個問題?

感謝所有提前。 Gary

回答

1

對於片段之間的通信,您可以使用EventBus。 EventBus使您的活動和片段鬆散耦合。

第一步是定義一個EventType。例如:CarSelectedEvent

在選擇Car(或您的案例中的某些文本類型)後,必須將CarSelectedEvent發佈到EventBus上。 例子:

eventBus.post(new CarSelectedEvent("volvo")); 

所有片段或有興趣的事件活動,必須實現一個名爲方法:

onEvent(CarSelectedEvent event){ 
... update your view 
} 

假設你有3個片段展示車的細節,每一個片段接收CarSelectedEvent和可更新視圖。從屏幕中刪除片段時(例如,在較小的屏幕或屏幕上旋轉),邏輯不會改變。唯一的區別是接收事件的碎片較少。

你可以在https://github.com/greenrobot/EventBus找到更多關於EventBus的信息。

+0

謝謝你。查看了github上的EventBus並下載了zip文件。愚蠢的問題可能,但我仍然在Android開發世界學習,我如何在日食中「插入」事件總線到我的應用程序?對不起,如果我問一個愚蠢的問題。 – Gary

+1

將jar放入項目的libs文件夾中,並在Eclipse中添加jar依賴項。在http://www.slideshare.net/greenrobot/eventbus-for-android-15314813上,您可以找到關於EventBus的演示文稿。 – userM1433372

+0

好的,謝謝你,我會在週末試一試。有一個好的一切! – Gary