发送数据
//Activity传值,通过Bundle
Bundle bundle = new Bundle();
bundle.putString("MainActivity", "Hello,Fragment");
//首先有一个Fragment对象 调用这个对象的setArguments(bundle)传递数据
myFragment.setArguments(bundle);
//点击按钮接受Fragment传回来的值
btn_send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = myFragment.getArguments();
String result = bundle.getString("MyFragment");
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
});
接收数据
//点击按钮接收Activity传过来的值
btn_fragment.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = getArguments();
String result = bundle.getString("MainActivity");
Toast.makeText(getActivity(), result, Toast.LENGTH_LONG).show();
}
});
//Fragment回传值给Activity
getArguments().putString("MyFragment", "Hello,Activity");