2016-01-27 218 views
0

我正在開發一個Android應用程序,我在片段中獲取了一些數據,並且我想在其他片段中使用它們。 所以我一直在尋找創建一個包,用一個簡單的getBasicInfos()方法返回我的包,然後將其發送到我的其他片段得到它的活動。 但問題是,我不能在我的活動使用此方法。Android從片段發送數據活動

fragment = new DashboardFragment(); 
      fragment.getBasicInfos(); //Does not recognize the method 
      toolbar.setTitle(getResources().getString(R.string.dashboard)); 
      break; 

我想知道是否有更好的方法,或者更簡單。

+1

提示:你必須使用回調方法。 – kishorepatel

+0

是''片段是'Fragment'類對象或''DashboardFragment類,這是'Fragment'的子類? –

+0

閱讀http://developer.android.com/training/basics/fragments/communicating.html – Raghunandan

回答

2

創建FragmentInterface和實現該接口在Activity然後同時實例化fragment = new DashboardFragment(this);通過這爲聽衆和Fragment constructor保存此

public DashboardFragment(FragmentListener listener) { 
    this.listener = listener; 
} 

然後使用這個監聽器將數據傳遞到您的activity

希望這有助於。

+0

我找到了另一種方法,我創建了一個公共方法setBundle(Bundle basicInfos),然後我把它叫做我的片段:) –

+0

這不是首選和有效的方法。 –

+0

好的,我會實施你的例子謝謝你! –

相關問題