Activity和Fragment两两之间的数据传递

来源:互联网 发布:photoshop有没有mac版 编辑:程序博客网 时间:2024/04/30 09:43

一、Activity之间传递数据

1、使用Intent传递一般数据(如字符串)

(1)发送数据
  1. Intent intent = new Intent(this,SecondActivity.class);
  2. intent.putExtra("data","sldkjfoei");
  3. startActivity(intent);
(2)接收数据
  1. Intent intent = getIntent();
  2. String data = intent.getStringExtra("data");

2、传递Bundle

(1)发送数据
  1. Intent intent = new Intent(this,SecondActivity.class);
  2. Bundle bundle = new Bundle();
  3. bundle.putString("data","将数据放到Bundle中");
  4. intent.putExtra("bundle",bundle);
  5. startActivity(intent);
(2)接受数据
  1. Intent intent = getIntent();
  2. Bundle bundle = intent.getBundleExtra("bundle");
  3. bundle.getString("data");

3、传递对象

(1)这个对象要实现序列化
(2)发送一个实现了序列化的Student类对象
  1. Intent intent = new Intent(this, SecondActivity.class);
  2. Student student = new Student("name",12,"gender");
  3. intent.putExtra("student",student);
  4. startActivity(intent);
(3)接受对象
  1. Intent intent = getIntent();
  2. Serializable student = intent.getSerializableExtra("student");

4、从Activity返回数据

(1)启动另一个Activity用startActivityForResult()
  1. startActivityForResult(intent, 0);//这里采用startActivityForResult来做跳转,此处的0为一个依据,可以写其他的值,但一定要>=0
(2)在另一个Activity中调用setResult方法,将要返回的数据传进来
  1. setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent,当然也可以自己定义新的Bundle
  2. finish();//此处一定要调用finish()方法
(3)在原Activity中重写onActivityResult()方法获取数据
  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  2. switch (resultCode) { //resultCode为回传的标记,我在B中回传的是RESULT_OK
  3. case RESULT_OK:
  4. Bundle b = data.getExtras(); //data为B中回传的Intent
  5. String str = b.getString("str1");//str即为回传的值
  6. break;
  7. default:
  8. break;
  9. }
  10. }

二、Activity与Fragment之间的交互(Fragment依赖于这个Activity)

1、Fragment获取Activity中的数据

1.1 Activity创建Fragment实例时传递数据

(1)MyFragment中写一个创建实例的方法,在方法中使用Bundle存储Activity传过来的数据
  1. public static MyFragment newInstance(String data){
  2. MyFragment myFragment = new MyFragment();
  3. Bundle bundle = new Bundle();
  4. bundle.putString("id",data);
  5. myFragment.setArguments(bundle);
  6. return myFragment;
  7. }
(2)在MyFragment的onCreateView()方法中获取数据
  1. @Override
  2. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  3. Bundle bundle = getArguments();
  4. String text = bundle.getString("id");
  5. return super.onCreateView(inflater, container, savedInstanceState);
  6. }
(3)在Activity中创建MyFragment实例,传入需要传递给MyFragment的数据
  1. //这里只需要直接调用这个方法,就创建了一个fragment
  2. fragment = MyFragment.newInstance("这里是要传递给MyFragment的数据");


1.2 Activity中实例化Fragment后发送数据

(1)Activity中:
  1. MyFragment fragment = new MyFragment();
  2. Bundle bundle = new Bundle();
  3. bundle.putString("id","从Activity中发送到Fragment的数据");、
  4. fragment.setArguments(bundle);
(2)MyFragment中:
  1. Bundle bundle = getArguments();
  2. String text = bundle.getString("id"));


1.3 在Fragment中定义回调接口,Activity中实现接口

(1)在MyFragment中定义回调接口:
  1. interface MyFragmengListener{
  2. void onCallBack();
  3. }
  4. MyFragmengListener fragmengListener = null;
(2)在MyFragment中需要的地方调用回调方法,比如在一个Button的点击事件中
  1. btn.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v) {
  4. fragmengListener.onCallBack();
  5. }
  6. });
(3)在Activity中实现回调接口,在回调方法中编写要执行的操作或设置要传递的数据
  1. public class MainActivity extends AppCompatActivity implements MyFragment.MyFragmengListener {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. }
  7. @Override
  8. public void onCallBack() {
  9. // 可以做很多操作,比如启动另一个Fragment,发送数据到Fragment中等等
  10. Toast.makeText(getApplicationContext(),"Fragment获取到Activity中的数据",Toast.LENGTH_SHORT).show();
  11. }
  12. }


1.4 使用剪切板

                    (1)发送数据的Activity中
  1. Person person = new Person("wulianghuan","22");
  2. //将对象转换成字符串
  3. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  4. String base64String = "";
  5. try {
  6. ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
  7. objectOutputStream.writeObject(person);
  8. base64String = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
  9. objectOutputStream.close();
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. //从Android系统中调用剪切板的服务
  14. ClipboardManager clipboardManager = (ClipboardManager)
  15. getSystemService(Context.CLIPBOARD_SERVICE);
  16. //在剪切板中放入要传递的数据
  17. clipboardManager.setText(base64String);
  18. //定义一个意图
  19. Intent intent = new Intent(MainActivity.this,OtherActivity.class);
  20. startActivity(intent);
                    (2)接受数据的Activity
  1. //从Android系统中调用剪切板的服务
  2. ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
  3. String getString = clipboardManager.getText().toString();
  4. //字符串还原成对象
  5. byte[] base64_byte = Base64.decode(getString, Base64.DEFAULT);
  6. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64_byte);
  7. try {
  8. ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
  9. Person person = (Person)objectInputStream.readObject();
  10. Log.i("OtherActivity", person.toString());
  11. //设置文本框的数据
  12. text_name.setText(person.toString());
  13. } catch (StreamCorruptedException e) {
  14. e.printStackTrace();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. } catch (ClassNotFoundException e) {
  18. e.printStackTrace();
  19. }

1.5 发送广播

1.6 使用静态变量


2、Activity获取Fragment中的数据

2.1 发送广播

                    (1)创建一个广播管理类
  1. /**
  2. * 广播管理类:注册广播、注销广播、发送广播
  3. * @author weizh_000
  4. * @date 2016-8-29
  5. */
  6. public class BroadCastManager {
  7. private static BroadCastManager broadCastManager = new BroadCastManager();
  8. public static BroadCastManager getInstance() {
  9. return broadCastManager;
  10. }
  11. //注册广播接收者
  12. public void registerReceiver(Activity activity,
  13. BroadcastReceiver receiver, IntentFilter filter) {
  14. activity.registerReceiver(receiver, filter);
  15. }
  16. //注销广播接收者
  17. public void unregisterReceiver(Activity activity,
  18. BroadcastReceiver receiver) {
  19. activity.unregisterReceiver(receiver);
  20. }
  21. //发送广播
  22. public void sendBroadCast(Activity activity, Intent intent) {
  23. activity.sendBroadcast(intent);
  24. }
  25. }
                    (2)在Fragment中发送广播
  1. public class MyFragment extends Fragment {
  2. private String orderid = "85465465";
  3. @Override
  4. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  5. Bundle savedInstanceState) {
  6. //发送广播
  7. Intent intent = new Intent();
  8. intent.putExtra("order", orderid);
  9. intent.setAction("fragment_home_left");
  10. BroadCastManager.getInstance().sendBroadCast(getActivity(), intent);
  11. return super.onCreateView(inflater, container, savedInstanceState);
  12. }
  13. }
                (3)在Activity中接收广播
  1. public class MainActivity extends ActionBarActivity {
  2. private LocalReceiver mReceiver;
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.activity_main);
  7. //接收广播
  8. try {
  9. IntentFilter filter = new IntentFilter();
  10. filter.addAction("fragment_home_left");
  11. mReceiver = new LocalReceiver();
  12. BroadCastManager.getInstance().registerReceiver(this,
  13. mReceiver, filter);//注册广播接收者
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. class LocalReceiver extends BroadcastReceiver{
  19. @Override
  20. public void onReceive(Context context, Intent intent) {
  21. //收到广播后的处理
  22. String orderid = intent.getStringExtra("order");
  23. loadData(orderid);
  24. }
  25. }
  26. private void loadData(String orderid){
  27. }
  28. @Override
  29. protected void onDestroy() {
  30. BroadCastManager.getInstance().unregisterReceiver(this,mReceiver);//注销广播接收者
  31. super.onDestroy();
  32. }
  33. }

2.2 Activity中使用Fragment对象获取数据

如果没有Fragment对象可以使用getFragmentByTag()方法来获取对象

三、Fragment之间的交互

1、依赖于同一个Activity的Fragment

1.1 发送广播

1.2 先获取到依赖的Activity,在获取到对应的Fragment

(1)发送数据
  1. ft.hide(getActivity().getSupportFragmentManager().findFragmentByTag(“”));
  2. SearchProjectFragment sf = new SearchProjectFragment();
  3. Bundle bundle = new Bundle();
  4. bundle.putString("key", Projsid);
  5. sf.setArguments(bundle);
  6. ft.add(R.id.fragmentRoot, sf, SEARCHPROJECT);
  7. ft.addToBackStack(SEARCHPROJECT);
  8. ft.commit();
                    (2)接收数据
  1. String string = getArguments().getString("key");

1.3 使用EventBus


2、依赖于不同的Activity的Fragment

2.1 发送广播

2.2 综合上述传递方式

                     Activity01获取Fragment01中的数据然后发送给Acticity02,Fragment02从Activity02获取从Activity01获取到的数据













0 0