在使用Intent对象时,我们可以直接使用其putExtra()
方法添加不同类型的数据。我们还可以将这些额外的数据放入一个Bundle
对象中,并将其添加到Intent
中。那么,如果我们可以直接使用Intent
来完成这些操作,为什么还需要Bundle
呢?
在使用Intent对象时,我们可以直接使用其putExtra()
方法添加不同类型的数据。我们还可以将这些额外的数据放入一个Bundle
对象中,并将其添加到Intent
中。那么,如果我们可以直接使用Intent
来完成这些操作,为什么还需要Bundle
呢?
正如您所看到的,Intent
在内部将它存储在一个Bundle
中。
public Intent putExtra(String name, String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}
Bundle
中,并在需要相同参数集时简单地使用intent.putExtras(mBundle)
。这将使更改代码更加容易,例如,如果其中一个参数在您的代码中变得过时。public class MyActivity {
private Bundle mBundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
mBundle = new Bundle();
mBundle.putString("parameter1", value1);
mBundle.putString("parameter2", value2);
}
private void openFirstActivity() {
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtras(mBundle);
startActivity(intent);
}
private void openSecondActivity() {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtras(mBundle);
startActivity(intent);
}
}
OBS:如前所述,Intent
将参数存储在内部的Bundle
中。值得注意的是,当您调用putExtras
时,内部的Intent bundle并不指向同一个对象,而是创建所有变量的副本,使用类似于这样的简单for
:
for (int i=0; i<array.mSize; i++) {
put(array.keyAt(i), array.valueAt(i));
}