Fragment与Activity的通信(回调),Fragment间的通信
一、消息Fragment-->Activity
1、Fragment启动Activity时通过Intent将数据传递过去,这种方法每次都要重启Activity。
2、通过回调方法:
2.1 普通的回调方法。
Fragment类中定义方法switch:
- private void switch(Fragment f) {
- if(f != null){
- if(getActivity() instanceof MainActivity){
- ((MainActivity)getActivity()).switchFragment(f);
- }
- }
- }
MainActivity类中对应的回调方法switchFragment(Fragment f)完成响应。
2.2 通过接口实现回调:
2.2.1 在Fragment类中定义接口及抽象方法,并在onAttach方法中添加如下代码:
- private OnFragmentChangeListener mCallBack;
- public interface OnFragmentChangeListener {
- public void onTabSwitch(int position);
- }
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
- //确保包含Fragment的Activity已经实现了回调接口,否则抛出异常
- try {
- mCallBack = (OnFragmentChangeListener) activity;
- } catch (Exception e) {
- throw new ClassCastException(activity.toString()
- + " must implement OnFragmentChangeListener");
- }
- }
2.2.2 在Activity中实现上面的接口:
- public class TestActivity extends Activity implements
- MyFragment.OnFragmentChangeListener {
- @Override
- public void onTabSwitch(int position) {
- //此处接收事件的回调
- }
- }
2.2.3 在Fragment将信息发送给父Activity:
- mCallBack.onTabSwitch(pos);
二、消息从Activity-->Fragment
1、通过实例化一个Fragment
在Activity中设置如下代码携带参数传递给Fragment:
- Fragment2 newFragment = new Fragment2();
- Bundle args = new Bundle();
- args.putInt(Fragment2.ARG_KEY, position);
- newFragment.setArguments(args);
- getFragmentManager().beginTransaction().replace(R.id.frame, newFragment).commit();
或者通过构造方法将数据传递给Fragment(官方不推荐):
- Fragment2 newFragment = new Fragment2(arg1,arg2);
推荐做法:
1.1在Fragment中
- public static MyFragment newInstance(String userName, String password) {
- MyFragment frgmt = new MyFragment();
- Bundle args = new Bundle();
- args.putString("userName", userName);
- args.putString("password", password);
- frgmt.setArguments(args);
- return frgmt;
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (null != getArguments()) {
- String userName = getArguments().getString("userName");
- String password = getArguments().getString("password");
- }
- }
1.2Activity中调用:
- MyFragment myFragment = MyFragment.newInstance("myName", "myPsw");
2、通过findFragmentById()或者findFragmentByTag()方法找到Fragment的实例:
- MyFragment fragment = (MyFragment) getFragmentManager().findFragmentById(R.id.frame);
- if(fragment!=null){
- fragment.frgmtFunc();
- }
参考自:http://blog.csdn.net/xyz_lmn/article/details/8631195#t1

浙公网安备 33010602011771号