2013-10-12 109 views
7

我知道的一種方法是通過activity.We可以將數據從片段發送到活動並將活動發送到片段有沒有其他方法。如何將數據從一個片段傳輸到另一個片段android

+0

使用接口與主機活動進行通信然後傳輸數據t從活動 – Raghunandan

+0

^的片段不,不這樣做.. 看到這個.. [http://stackoverflow.com/questions/13733304/ callback-a-a-a-a -fragment](http://stackoverflow.com/questions/13733304/callback-to-a-fragment-from-a-dialogfragment) – Zyoo

+0

@Zyoo爲什麼會這樣? – Raghunandan

回答

4

從文檔

引用通常你會想要一個片段與另一個通信,例如改變基於用戶事件的內容。 所有片段到片段的通信都是通過關聯的活動完成的。兩個碎片不應該直接通信。

我建議您按照文檔的方法,我還沒有嘗試過任何其他替代

對於chekc的文檔的詳細信息和示例中的以下鏈接

http://developer.android.com/training/basics/fragments/communicating.html

+0

如果我使用'setRetainInstance(true)',該怎麼辦?它是否仍然需要先傳遞給活動? – Zyoo

+0

是的。檢查文檔http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean) – Raghunandan

14

要傳遞數據從一個片段到另一個Bundle將有所幫助。

LifeShapeDetailsFragment fragment = new LifeShapeDetailsFragment(); // object of next fragment 
Bundle bundle = new Bundle(); 
bundle.putInt("position", id); 
fragment.setArguments(bundle); 

然後push/call next Fragments.

和代碼下一個片段:

Bundle bundle = this.getArguments(); 
int myInt = bundle.getInt("position", 0); 
+2

根據原始的android開發者文檔,這種方法是錯誤的。我們應該使用活動在兩個片段之間進行通信。這裏是鏈接:http://developer.android.com/intl/vi/training/basics/fragments/communicating.html – salih

0

允許片段通過使用活動作爲其中介是一種常見的最佳實踐使用片段時相互通信。請訪問http://developer.android.com/guide/components/fragments.html以瞭解有關此重要模式的更多詳情。無論何時您需要與另一個片段進行交互,您應該始終在片段的活動中使用一種方法,而不是直接訪問其他片段。從另一個片段訪問片段唯一有意義的是當你知道你不需要在另一個活動中重用你的片段時。假設您將重用它們而不是將它們硬編碼到彼此,您幾乎總是應該編寫片段。

4

有兩種方法我會考慮可行的:

一個 .Communicate與你所屬的活動和轉發消息通過到,擁有活動的其他片段,對細節可以詮釋他的官方Android文檔在這裏找到:

http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

報價:

在某些情況下,您可能需要使用片段與 活動共享事件。一個好的方法是在片段內定義一個回調接口 ,並要求主機活動實現它。 當活動通過接口收到回調時,它可以根據需要與佈局中的其他片段共享信息。

通信接口可以是這個樣子:

public interface IActionListener{ 

    //You can also add parameters to pass along etc 
    public void doSomething(); 
} 

片段會是這個樣子:

public class MyFragment extends Fragment{ 

private WeakReference<IActionListener> actionCallback; 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     try { 
      // This makes sure that the container activity has implemented 
      // the callback interface. If not, it throws an exception 
      actionCallback = new WeakReference<IActionListener>((IActionListener) activity); 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() + " must implement IActionListener."); 
     } 
    } 
} 

我在這裏使用的WeakReference但是這真的取決於你。現在可以使用actionCallback與擁有的活動進行通信並調用IActionListener中定義的方法。

所屬的活動應該是這樣的:

public class MyActivity extends ActionBarActivity implements IActionListener { 

public void doSomething(){ //Here you can forward information to other fragments } 

} 

。現在至於第二種方法 - 您可以使用接口將片段直接相互通信 - 這樣您就不必知道與您通話的片段的確切類別,從而確保了鬆耦合。

設置如下:您有兩個片段(或更多)和一個活動(啓動第二個片段)。我們有一個界面,可以讓Fragment 2在完成任務後向Fragment 1發送響應。爲了簡便起見,我們只是重新使用我A.

這裏定義的接口是我們的片段1:

public class FragmentOne extends Fragment implements IActionListener { 

public void doSomething() {//The response from Fragment 2 will be processed here} 

} 

使用要求它擁有活動在A.片段1所描述的方法啓動Fragment 2.然而,Activity將沿着Fragment 1作爲參數傳遞給Fragment 2,因此Fragment 2可以稍後間接訪問Fragment 1併發送回復。讓我們來看看活動如何PREPS片段2:

public class MyActivity extends ActionBarActivity { 

    // The number is pretty random, we just need a request code to identify our request later 
    public final int REQUEST_CODE = 10; 
    //We use this to identify a fragment by tag 
    public final String FRAGMENT_TAG = "MyFragmentTag"; 

     @Override 
     public void onStartFragmentTwo() { 
      FragmentManager manager = getSupportFragmentManager(); 
      FragmentTransaction transaction = manager.beginTransaction(); 

        // The requesting fragment (you must have originally added Fragment 1 using 
        //this Tag !) 
      Fragment requester = manager.findFragmentByTag(FRAGMENT_TAG); 
        // Prepare the target fragment 
      Fragment target = new FragmentTwo(); 
        //Here we set the Fragment 1 as the target fragment of Fragment 2's  
        //communication endeavors 
      target.getSelf().setTargetFragment(requester, REQUEST_CODE); 

        // Hide the requesting fragment, so we can go fullscreen on the target 
      transaction.hide(requester); 
      transaction.add(R.id.fragment_container, target.getSelf(), FRAGMENT_TAG); 
      transaction.addToBackStack(null); 

      transaction.commit(); 
     } 
    } 

提示:我使用的是支持的框架,因此,如果您> Android 3.0的,你可以簡單地使用,而不是ActionBarActivity FragmentActivity獨自去開發。

現在正在啓動FragmentTwo,讓我們來看看FragmentTwo如何與FragmentOne通信:

public class FragmentTwo extends Fragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     if(savedInstanceState != null){ 
      // Restore our target fragment that we previously saved in onSaveInstanceState 
      setTargetFragment(getActivity().getSupportFragmentManager().getFragment(savedInstanceState, TAG), 
        MyActivity.REQUEST_CODE);   
     } 

     return super.onCreateView(inflater, container, savedInstanceState); 
    } 

    @Override 
    public void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
     // Retain our callback fragment, the TAG is just a key by which we later access the fragment 
     getActivity().getSupportFragmentManager().putFragment(outState, TAG, getTargetFragment()); 
    } 

    public void onSave(){ 
     //This gets called, when the fragment has done all its work and is ready to send the reply to Fragment 1 
     IActionListener callback = (IActionListener) getTargetFragment(); 
     callback.doSomething(); 
    } 

} 

現在DoSomething的的片段1()的執行將被調用。

+0

我認爲你的第一個代碼片段中存在代碼錯誤。你可以在一個地方調用你的WeakReference「ActionListener」,在另一個地方調用「ActionCallback」。你能檢查一下嗎? –

+0

@ParthShah哦謝謝!把它寫成我的頭頂,並沒有仔細檢查變量名稱 - 再次感謝你,我改正了它 – AgentKnopf

+0

儘管如此,答案很棒,有很多很棒的例子!做得好! –

2

這裏是解決方案,

遵循以下步驟:

1 2.implements使用這個接口

for.e.g 
    public class OrderDetail extends ActionBarActivity implements TitleChangeListener 

3您的活動創造這樣的

接口.in此活動創建於onUpdateTitle()

 public void onUpdateTitle(String title) 
     { 
     //here orderCompletedDetail is the object second fragment name ,In which fragement I want send data. 

     orderCompletedDetail.setTitle(title); 
     } 

4.現在,在Fragment中寫一些代碼。

  public class OrderPendingDetail extends Fragment 
      { 
      private View rootView; 
      private Context context; 
      private OrderDetail orderDetail; 
      @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
      { 
      rootView = inflater.inflate(R.layout.order_pending_detail, container, false); 
      context = rootView.getContext(); 

      //here OrderDetail is the name of ActionBarActivity 
      orderDetail = (OrderDetail) context; 

     //here pass some text to second Fragment using button ClickListener 
      but_updateOrder.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) 
       { 
       // here call to Activity onUpdateTitle() 
       orderDetail.onUpdateTitle("bridal"); 
       } 
     }); 
     return rootView; 
     } 
     } 

5.write一些代碼在第二片段的setTitle()

  public void setTitle(String title) 
      { 
      TextView orderCompeted_name=(TextView)rootView.findViewById(R.id.textView_orderCompeted_name); 
      orderCompeted_name.setText(title); 
      //here you see the "bridal" value for TextView 
      } 

在當你點擊那個時候它示出了在第二片段值片段一個按鈕該溶液中。 我希望這會對你有所幫助。

相關問題