一、消息Fragment-->Activity

1、Fragment启动Activity时通过Intent将数据传递过去,这种方法每次都要重启Activity。

2、通过回调方法:

 

Fragment类中定义方法switch:

1. private void switch(Fragment f) {  
2. if(f != null){  
3. if(getActivity() instanceof MainActivity){  
4.             ((MainActivity)getActivity()).switchFragment(f);  
5.         }  
6.     }  
7. }

       MainActivity类中对应的回调方法switchFragment(Fragment f)完成响应。

1. private OnFragmentChangeListener mCallBack;  
2.   
3. public interface OnFragmentChangeListener {  
4. public void onTabSwitch(int position);  
5. }  
6.   
7. @Override  
8. public void onAttach(Activity activity) {  
9. super.onAttach(activity);  
10. //确保包含Fragment的Activity已经实现了回调接口,否则抛出异常  
11. try {  
12.         mCallBack = (OnFragmentChangeListener) activity;  
13. catch (Exception e) {  
14. throw new ClassCastException(activity.toString()  
15. " must implement OnFragmentChangeListener");  
16.     }  
17. }


1. public class TestActivity extends Activity implements  
2.         MyFragment.OnFragmentChangeListener {  
3. @Override  
4. public void onTabSwitch(int position) {  
5. //此处接收事件的回调  
6.     }  
7. }


1. mCallBack.onTabSwitch(pos);

 

 

二、消息从Activity-->Fragment

1、通过实例化一个Fragment

    在Activity中设置如下代码携带参数传递给Fragment:

1. Fragment2 newFragment = new Fragment2();  
2. Bundle args = new Bundle();  
3. args.putInt(Fragment2.ARG_KEY, position);  
4. newFragment.setArguments(args);  
5. getFragmentManager().beginTransaction().replace(R.id.frame, newFragment).commit();

   或者通过构造方法将数据传递给Fragment(官方不推荐):

1. Fragment2 newFragment = new Fragment2(arg1,arg2);

推荐做法:

1.1在Fragment中

1. public static MyFragment newInstance(String userName, String password) {  
2. new MyFragment();  
3. new Bundle();  
4. "userName", userName);  
5. "password", password);  
6.         frgmt.setArguments(args);  
7. return frgmt;  
8.     }  
9.   
10. @Override  
11. public void onCreate(Bundle savedInstanceState) {  
12. super.onCreate(savedInstanceState);  
13. if (null != getArguments()) {  
14. "userName");  
15. "password");  
16.         }  
17.     }

1.2Activity中调用:

1. MyFragment myFragment = MyFragment.newInstance("myName", "myPsw");

 

2、通过findFragmentById()或者findFragmentByTag()方法找到Fragment的实例:

1. MyFragment fragment = (MyFragment) getFragmentManager().findFragmentById(R.id.frame);  
2. if(fragment!=null){  
3.     fragment.frgmtFunc();  
4. }