You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Intent传递Boolean列表并从Intent中取回?

嘿,这个问题我刚好实操过,给你两种实用的解决方案,都能轻松搞定:

方法一:利用Serializable接口(最简单直接)

因为ArrayList和Boolean都实现了Serializable接口,所以可以直接通过putSerializableExtra传递:

发送端代码

// 初始化你的Boolean列表
List<Boolean> booleanList = new ArrayList<>();
booleanList.add(true);
booleanList.add(false);
// 其他添加操作...

Intent intent = new Intent(YourCurrentActivity.this, TargetActivity.class);
// 传入列表,注意这里要强制转换为Serializable
intent.putExtra("BOOLEAN_LIST", (Serializable) booleanList);
startActivity(intent);

接收端代码

在目标Activity的onCreate()方法中取回:

Intent receivedIntent = getIntent();
if (receivedIntent != null) {
    // 强制转换回List<Boolean>
    List<Boolean> booleanList = (List<Boolean>) receivedIntent.getSerializableExtra("BOOLEAN_LIST");
    // 现在就可以使用这个列表啦
}

方法二:转成Integer列表传递(更高效)

如果追求更高的传输效率,可以把Boolean转成Integer(用1代表true,0代表false),借助Intent原生支持的putIntegerArrayListExtra方法:

发送端代码

List<Boolean> booleanList = new ArrayList<>();
booleanList.add(true);
booleanList.add(false);
// 其他添加操作...

// 把Boolean列表转成Integer列表
ArrayList<Integer> intList = new ArrayList<>();
for (Boolean b : booleanList) {
    intList.add(b ? 1 : 0);
}

Intent intent = new Intent(YourCurrentActivity.this, TargetActivity.class);
intent.putIntegerArrayListExtra("BOOLEAN_LIST_INT", intList);
startActivity(intent);

接收端代码

Intent receivedIntent = getIntent();
if (receivedIntent != null) {
    ArrayList<Integer> intList = receivedIntent.getIntegerArrayListExtra("BOOLEAN_LIST_INT");
    // 转回到Boolean列表
    List<Boolean> booleanList = new ArrayList<>();
    for (Integer i : intList) {
        booleanList.add(i == 1);
    }
    // 处理列表逻辑
}

一些小提醒

  • 建议把传递用的key定义成常量(比如public static final String BOOLEAN_LIST_KEY = "BOOLEAN_LIST";),避免拼写错误
  • 方法一中的强制转换要确保类型正确,避免抛出ClassCastException
  • 如果你的列表是不可变的(比如用Collections.unmodifiableList生成),只要它实现了Serializable就没问题,ArrayList是完全支持的

内容的提问来源于stack exchange,提问作者fmag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:27:04