【发布时间】:2011-09-24 08:23:12
【问题描述】:
在使用 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;
}
【讨论】:
有时您只需要将few variables 或values 传递给其他Activity,但是如果您有一个bunch of variable's or values 需要传递给各种Activities 怎么办。在这种情况下,您可以使用Bundle 并将Bundle 轻松传递给所需的Activity。而不是每次都传递单个变量。
【讨论】:
mExtras = new Bundle(); 这还不够有说服力吗?如果没有,请自行查看Intent.java的源代码。
假设您需要将Bundle 从一个Activity 传递给另一个。这就是Intent 允许您将Bundles 添加为额外字段的原因。
编辑:例如,如果您想将数据库中的一行与其他一些数据一起传递,则将此行放入Bundle 并将此Bundle 添加到@ 非常方便987654327@ 作为一个额外的字段。
【讨论】:
Bundle 你需要通过。你真的想将它逐个字段复制到Intent。如果Bundle 和Intent 的键会重叠?您无法了解人们所做的所有事情,因此请记住,您可以将 Bundle 放入 Intent 中,当您需要时,您就会知道该怎么做。
Bundle 中非常方便。在我的一个应用程序中,我使用Bundles 列表从数据库中传递几行。
Bundle 中添加很多变量的情况。通常人们在这种情况下创建Parcelable 对象。它更安全、更易于理解和维护。
我猜@Lalit 的意思是假设您的活动总是将相同的变量传递给不同的意图,您可以将所有这些变量存储在您的班级中的单个 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 包并不指向相同的对象,但创建所有变量的副本,使用简单的for 如下:
for (int i=0; i<array.mSize; i++) {
put(array.keyAt(i), array.valueAt(i));
}
【讨论】: