2014-07-17 85 views
1

我有一個正常的android活動,其中包含選擇列表視圖。當選擇一個選項時,它通過一個意圖啓動一個片段活動。該片段活動本身包含一個操作欄,由3個片段組成。Android:活動與片段活動之間的溝通

我想是基於在活動(其中包含的 選項列表視圖)的選擇做的是所選擇的位置號碼發送到片段的活性,因此所述3個片段

我發現了接口,但這些例子令人困惑,理解,有人可以幫我解決這個問題。我只想將選定的位置發送給其他片段。

回答

4

傳遞所選擇的位置從活動到FragmentActivity可以Bundle

你的意圖完成應該是這樣的:

Intent intent = new Intent(Activity.this, FragmentActivity.class); 
intent.putExtra("idforthevalue",selectedPOsition); 
startActivity(intent); 

然後在你的FragmentActivity可以檢索值:

Bundle extras = getIntent().getExtras(); 
    int position = 0; 
    if(extras != null) { 
     position = extras.getInt("idforthevalue"); 
    } 

而取決於你如何添加你的片段,你也可以通過FragmentActivit的Bundle傳遞這個值給他們Ÿ在FragmentTransaction

FragmentManager fragmentManager = getFragmentManager(); // or getSupportFragmentManager() if you are using compat lib 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 

FragmentX fragmentX = new FragmentX(); 
Bundle bundle = new Bundle(); 
bundle.putInt("idforthevalue", position); 
fragmentX.setArguments(bundle); 

fragmentTransaction.replace(id_of_container, fragmentX).commit(); 

而且又可以在片段

 Bundle bundle = getArguments(); 
     if(bundle != null) { 
      position = bundle.getInt("idforthevalue", 0); 
     } 

你可以做三個片段相同的檢索值。

+0

謝謝,工作很棒! – user3364963