课前预习
Android中的Bundle
Android中的Intent
假设需要将数据从页面A传递到B,然后再传递到C
Intent传值:
A页面中
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("_username",username);
intent.putExtra("_gender",gender);
intent.putExtra("_age",age);
startActivity(intent);
B页面中
//接收数据
Intent intent = getIntent();
String u = intent.getStringExtra("_username");
String g = intent.getStringExtra("_gender");
int a = intent.getIntExtra("_age",0);
//发送数据
Intent intent2 = new Intent(this,ThirdActivity.class);
intent2.putExtra("_username",u);
intent2.putExtra("_gender",g);
intent2.putExtra("_age",a);
startActivity(intent2);
C页面中
Intent intent = getIntent();
String u = intent.getStringExtra("_username");
String g = intent.getStringExtra("_gender");
int a = intent.getIntExtra("_age",0);
Log.d("Intent","姓名:"+u+",性别:"+g+",年龄:"+a);
可以看到,使用Intent传值需要在B页面将数据一条条取出来然后再一条条传输给C页面。
而使用Bundle的话,在B页面可以直接取出传输的Bundle对象然后传输给C页面
Bundle方式:
A页面中
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("_username", username);
bundle.putString("_gender", gender);
bundle.putInt("_age", age);
intent.putExtra("bundle", bundle);
startActivity(intent);
B页面中
//接收数据
Intent intent = getIntent();
Bundle bundle=intent.getBundleExtra("bundle");
//发送数据
Intent intent2 =new Intent(this,ThirdActivity.class);
intent2.putExtras(bundle);
startActivity(intent2);
C页面中
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String u = bundle.getString("_username");
String g = bundle.getString("_gender");
int a = bundle.getInt("_age");
Log.d("Intent", "姓名:" + u + ",性别:" + g + ",年龄:" + a);
总结:
Bundle可对对象进行操作,而Intent是不可以。Bundle相对于Intent拥有更多的接口,用起来比较灵活,但是使用Bundle也还是需要借助Intent才可以完成数据传递。总之,Bundle旨在存储数据,而Intent旨在传值