2015-05-12 68 views
1

我有一個內部的討論,關於在控制器活動內部的碎片內容之間共享信息的更好方式。在第一個經典的方法,你可以設置你什麼時候如下替換片段參數:Android碎片共享信息方式

   //Just now i'm inside Fragment 1 and i'll navigate to Fragment 2 
       Fragment newFragment = getFragmentManager().findFragmentByTag(Fragment2.TAG); 

       Bundle b = new Bundle(); 
       b.putBoolean("test1", true); 

       // Create new fragment and transaction 
       if(newFragment==null) 
        newFragment = Fragment2.newInstance(b); 

       FragmentTransaction transaction = getFragmentManager().beginTransaction(); 
       transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)//.setCustomAnimations(R.anim.enter_anim, R.anim.exit_anim) 
          .replace(R.id.fragment_place, newFragment, Fragment2.class.getName()) 
          .addToBackStack(newFragment.getClass().getName()) 
          .commit(); 

的newInstace方法確實如我上面的意思,所以,與setArguments:

public static Fragment2 newInstance(Bundle arguments){ 
    Fragment2 f = new Fragment2(); 
    if(arguments != null){ 
     f.setArguments(arguments); 
    } 
    return f; 
} 

但片段1和Fragment2它們都在ControllerActivity中,所以我也可以考慮通過在ControllerActivity中聲明屬性來共享在Fragment1中獲取的信息的第二種方法,以便我可以在活動中聲明以前的對象,如下所示任何片段:

編輯

public class ControllerActivity extends FragmentActivity{ 

int value = 5; 
... 

然後,我的片段裏面:

((SplashActivity)getActivity()).value = 10; //i can assign or recover value when i desire 

我的問題是什麼不便之處將有做的第二種方式。

+0

你會在你的應用程序中使用異步操作,它可以改變活動值? –

+0

你的意思是「片段間通信」嗎? – Paritosh

+0

我以這種方式知道的唯一的邪惡就是惡魔的靜態變量釋放!說了我不能拒絕使用它們。 – Skynet

回答

1

使用第二種方式編寫代碼很快。但問題是您必須將Activity轉換爲更具體的SplashActivity,其中value變量存在。如果您想將碎片與其他活動一起使用,或者您希望碎片成爲通用用戶界面組件,則必須使用interface來傳遞數據。

正如評論所說,波紋管鏈接提供了更多詳細的interface/callback方法:

希望這回答了你的問題。