1. Fragment可调用getActivity()方法获取它所在的Activity
2. Activity可以调用FragmentManage的findFragmentById()
或者findFragmentByTag()方法获取Fragment。
Activity-->Fragment:
在Activity中创建Bundle数据包,并且调用Fragment的setArgument
(Bundle bundle)方法将Bundle 传出。其中Bundle的put方法放入
数据,用getArgument方法接受数据,其中用该方法的.get()方法
接受。
Fragment-->Activity:
在Fragment中定义一个内部回调接口,再让包含该Fragment的Activity
实现该回调接口。这样Fragment可调用该回调方法将数据传给Activity
--------------------------------------------------------------------------------------------
public class MyFragment4 extends Fragment{
private TextView tv;
private String code = "Thank you ,Activity.";
public interface myListenner
{
public void thank(String code);
}
public myListenner listenner;
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
listenner=(myListenner) activity;
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment2, container,false);
tv= (TextView) view.findViewById(R.id.edittest4);
String text =getArguments().getString("name")+"";
tv.setText(text);
Toast.makeText(getActivity(),"接受的数据为"+ text, Toast.LENGTH_SHORT).show();
listenner.thank(code);
return view;
}
}
-------------------------------------------------------------------------------------------------------------------
接下来在Activity中实现该接口并且实现该该方法,即可实现传值。