2014-05-24 104 views

回答

2

從尾數documentation

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly. 

所以我建議是這樣的: 您有活動

public class MainActivity extends FragmentActivity{ 
    //On create stuff ..... 
    @Override 
public void onButtonPressed(String msg) { 
    // TODO Auto-generated method stub 
    LayOutTwo Obj=(LayOutTwo) getSupportFragmentManager().findFragmentById(R.id.frag_2); 
    Obj.setMessage(msg); 
} 
} 

兩個片段和一個相關聯的活動

代碼代碼佈局1:

Button but=(Button)root.findViewById(R.id.button1); 
    but.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      buttonListener.onButtonPressed("Message From First Fragment"); 
     } 
    }); 

代碼對於佈局2:

void setMessage(String msg){ 
    TextView txt=(TextView)root.findViewById(R.id.textView1); 
    txt.setText(msg); 
} 

這如何使用它的相關聯的活動容易地通過片段之間的數據。

希望這會有幫助

+0

感謝您的簡要說明。我們使用AsyncTask? –

+0

對不起,AsyncTask爲了什麼?用於傳遞數據?不,如果上述答案對您有幫助,請花點時間標記它是正確的。謝謝 –

相關問題