2014-05-24 66 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为了什么?用于传递数据?不,如果上述答案对您有帮助,请花点时间标记它是正确的。谢谢 –

相关问题