Android应用程序中的捆绑包是什么?什么时候使用?


当前回答

Bundle用于在活动之间传递数据。你可以创建一个bundle,将它传递给Intent来启动活动,然后可以从目标活动中使用。

其他回答

Bundle用于在活动之间共享数据, 在oncreate()方法中保存应用程序的状态,这样应用程序就会知道它在哪里停止了… 我希望它能帮助你:)

第一个活动:

String food = (String)((Spinner)findViewById(R.id.food)).getSelectedItem();
RadioButton rb = (RadioButton) findViewById(R.id.rb);
Intent i = new Intent(this,secondActivity.class);
i.putExtra("food",food);
i.putExtra("rb",rb.isChecked());

第二个活动:

String food = getIntent().getExtras().getString("food");
Boolean rb = getIntent().getExtras().getBoolean("rb");

bundle可以用来通过intent将任意数据从一个活动发送到另一个活动。当你广播一个Intent时,感兴趣的activity(和其他broadcastreceivers)会得到通知。一个intent可以包含一个Bundle,这样你就可以发送额外的数据。

bundle是键-值映射,因此在某种程度上它们类似于Hash,但它们并不严格限制于单个String / Foo对象映射。请注意,只有特定的数据类型被认为是“可打包的”,并且它们在Bundle API中被显式地拼写出来。

通过使用Bundle和Intent对象在活动之间传递数据。


首先创建一个Bundle对象

Bundle b = new Bundle();

然后,将存储在anystring中的字符串数据与bundle key "myname"关联起来

b.putString("myname", anystring);

现在,创建一个Intent对象

Intent in = new Intent(getApplicationContext(), secondActivity.class);

将bundle对象b传递给intent

in.putExtras(b);

开始第二项活动

startActivity(in);

在第二个活动中,我们必须访问从第一个活动传递的数据

Intent in = getIntent();

现在,您需要从包中获取数据

Bundle b = in.getExtras();

最后,获取与名为"myname"的键相关的字符串数据的值

String s = b.getString("myname");

使用bundle在intent对象的帮助下将数据从一个活动发送到另一个活动; 捆绑包保存可以是任何类型的数据。

现在我告诉它如何创建在两个活动之间传递数据的bundle。

第一步:第一个活动

Bundle b=new Bundle();

b.putString("mkv",anystring);

Intent in=new Intent(getApplicationContext(),secondActivity.class);

in.putExtras(b);

startActivity(in);

第二步:第二项活动

Intent in=getIntent();

Bundle b=in.getExtras();

String s=b.getString("mkv");

我认为这对你很有用...........