一、Activity之间传递数据
1、使用Intent传递一般数据(如字符串)
(1)发送数据
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("data","sldkjfoei");
startActivity(intent);
(2)接收数据
Intent intent = getIntent();
String data = intent.getStringExtra("data");
2、传递Bundle
(1)发送数据
Intent intent = new Intent(this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("data","将数据放到Bundle中");
intent.putExtra("bundle",bundle);
startActivity(intent);
(2)接受数据
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("bundle");
bundle.getString("data");
3、传递对象
(1)这个对象要实现序列化
(2)发送一个实现了序列化的Student类对象
Intent intent = new Intent(this, SecondActivity.class);
Student student = new Student("name",12,"gender");
intent.putExtra("student",student);
startActivity(intent);
(3)接受对象
Intent intent = getIntent();
Serializable student = intent.getSerializableExtra("student");
4、从Activity返回数据
(1)启动另一个Activity用startActivityForResult()
startActivityForResult(intent, 0);//这里采用startActivityForResult来做跳转,此处的0为一个依据,可以写其他的值,但一定要>=0
(2)在另一个Activity中调用setResult方法,将要返回的数据传进来
setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent,当然也可以自己定义新的Bundle
finish();//此处一定要调用finish()方法
(3)在原Activity中重写onActivityResult()方法获取数据
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
//resultCode为回传的标记,我在B中回传的是RESULT_OK
case RESULT_OK:
Bundle b = data.getExtras(); //data为B中回传的Intent
String str = b.getString("str1");//str即为回传的值
break;
default:
break;
}
}
二、Activity与Fragment之间的交互(Fragment依赖于这个Activity)
1、Fragment获取Activity中的数据
1.1 Activity创建Fragment实例时传递数据
(1)MyFragment中写一个创建实例的方法,在方法中使用Bundle存储Activity传过来的数据
public static MyFragment newInstance(String data){
MyFragment