如何获取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
相关产品推荐
相关产品推荐

