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

如何获取Android中Intent.putExtra()传入的键名(Tag/Name)?

Retrieving the Key Name (Not Its Value) from a Bundle in Android

No problem! Let's cover how to pull the key name ("CL2") instead of its associated value ("hello") from the Bundle you get in your target Activity.

When you pass data with intent.putExtra("CL2", "hello") and fetch the Bundle via getIntent().getExtras(), the Bundle class provides a keySet() method that returns all the keys stored in it as a Set<String>. This is exactly what you need to access the key names directly.

Step-by-Step Code Example

In your receiving Activity, use this code:

Bundle receivedBundle = getIntent().getExtras();
if (receivedBundle != null) {
    // Fetch all keys present in the Bundle
    Set<String> bundleKeys = receivedBundle.keySet();
    
    // Case 1: You're looking for a specific key ("CL2")
    for (String key : bundleKeys) {
        if ("CL2".equals(key)) {
            // 'key' now holds the string "CL2" — your desired key name
            // Perform your logic with this key here
            break;
        }
    }
    
    // Case 2: You know the Bundle only contains this one key
    if (!bundleKeys.isEmpty()) {
        String targetKey = bundleKeys.iterator().next();
        // 'targetKey' will be "CL2" in your scenario
    }
}

Important Reminders

  • Always null-check the Bundle: If no extras were passed, getExtras() returns null, so skipping this check could cause a crash.
  • If you already know the key name ("CL2") beforehand, you can just use that string directly—but this approach is essential for dynamic cases where you don't know which keys are in the Bundle.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:50:42