Android应用程序中的捆绑包是什么?什么时候使用?
当前回答
通过使用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");
其他回答
Update: When it comes to Android, there are two completely unrelated meanings to the term "bundle". One is detailed in my original answer below. The other is an app bundle. This is a newer archive file format (ending in .aap) that contains an Android app plus some additional metadata. You can upload an app bundle file instead of an application APK file to distribute your app through Google Play. App bundles have certain advantages over .apk files, but may not be compatible with other app stores (such as the Amazon App Store). These advantages are described in the documentation link included in my original answer.
最初的回答:
Bundle非常类似于将字符串键映射到值的Java Map对象。它用于在活动和其他应用程序组件之间传递信息。框架还使用它来捕获和恢复状态信息。
Android不使用普通的旧Map对象的原因是Map太灵活了;它可以包含不能序列化的对象(例如I/O流)。Bundle API限制了可以添加到Bundle中的对象类型,以保证Bundle的内容是可序列化的。Android框架依赖于这个属性。
我建议您阅读有关应用程序基础的文档。这解释了什么是捆绑包和意图,以及它们的用途。
通过使用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");
第一个活动:
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用于在活动之间传递数据。你可以创建一个bundle,将它传递给Intent来启动活动,然后可以从目标活动中使用。
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。