Activity之间通过intent交互

intent是不同组件之间用于传递消息的对象,一般用于跳转活动,启动活动,启动服务等。

发送数据(方式1)

java 复制代码
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtra("key",value);
startActivity(intent);

这是一个最简单的模板。创建一个intent对象并传入两个参数,都是Activity类型。第一个参数代表目前所在的Activity,第二个参数代表要开启(跳转到的)Activity。intent.putExtra(),以键值对的方式传入一些数据。

value(值) 的类型可以是基本类型,String类型也可以是Serializable类型。最后一种类型允许使用者将对象序列化并作为参数传到目标活动中去。

发送数据(方式2)

java 复制代码
Bundle bundle=new Bundle();
bundle.putString("key1",value1);
bundle.putInt("key2",value2);
bundle.putSerializable("key3",value3);
...
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtras(bundle);
startActivity(intent);

另外一种方式就是将数据放到bundle对象中,再将bundle对象通过intent的putExtras()方法传入intent中。

目标活动接收数据(方式1)

java 复制代码
Intent intent=getIntent();
String str=intent.getStringExtra("key1");
int integer=intent.getIntExtra("key2");
Cls obj=(Cls)intent.getSerializableExtra("key3");

getIntent()方法是Activity里面自带的方法

另外要注意的是,如果想将一个对象序列化传到目标活动中去的话,你需要让这个类实现Serializable接口,而且这个类里面所涉及到的类也要实现该接口,不然就会报错。

接收数据方式2

java 复制代码
Intent intent=getIntent();
Bundle bundle=intent.getExtras();
String str=bundle.get("key1");
int integer=bundle.getInt("key2");
Cls obj=(Cls)bundle.getSerializable("key3");

对应的是通过bundle发送数据的方法

相关推荐
q***071416 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
q***498616 小时前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
沐浴露z18 小时前
【微服务】基本概念介绍
java·微服务
Z3r4y19 小时前
【代码审计】RuoYi-4.7.3&4.7.8 定时任务RCE 漏洞分析
java·web安全·ruoyi·代码审计
q***829120 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
Kuo-Teng20 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
Jooou20 小时前
Spring事务实现原理深度解析:从源码到架构全面剖析
java·spring·架构·事务
盖世英雄酱5813621 小时前
commit 成功为什么数据只更新了部分?
java·数据库·后端
码上淘金21 小时前
在 YAML 中如何将 JSON 对象作为字符串整体赋值?——兼谈 Go Template 中的 fromJson 使用
java·golang·json