
Android
如何在 Android 活动之间传递 HashMap
HashMap<String, String> hashMap = new HashMap<>();hashMap.put("key1", "value1");hashMap.put("key2", "value2");2. 创建一个Intent对象,并将HashMap转化为Bundle对象:Intent intent = new Intent(this, TargetActivity.class);Bundle bundle = new Bundle();bundle.putSerializable("hashMap", hashMap);intent.putExtras(bundle);3. 启动目标活动:startActivity(intent);4. 在目标活动中获取传递的HashMap对象:
Bundle bundle = getIntent().getExtras();HashMap<String, String> hashMap = (HashMap<String, String>) bundle.getSerializable("hashMap");注意:在将HashMap转化为Bundle对象时,需要注意HashMap中的值必须实现Serializable接口,否则会抛出NotSerializableException异常。这样,我们就成功地在两个活动之间传递了HashMapJavapublic class MAInActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setcontentView(R.layout.activity_mAIn); // 创建HashMap对象,并添加键值对 HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("key1", "value1"); hashMap.put("key2", "value2"); // 创建Intent对象,并将HashMap转化为Bundle对象 Intent intent = new Intent(this, TargetActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("hashMap", hashMap); intent.putExtras(bundle); // 启动目标活动 startActivity(intent); }}TargetActivity.Java:Javapublic class TargetActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setcontentView(R.layout.activity_target); // 获取传递的HashMap对象 Bundle bundle = getIntent().getExtras(); HashMap<String, String> hashMap = (HashMap<String, String>) bundle.getSerializable("hashMap"); // 输出HashMap中的键值对 for (Map.Entry<String, String> entry : hashMap.entrySet()) { Log.d("HashMap", "Key: " + entry.getKey() + ", Value: " + entry.getValue()); } }}以上代码中,MAInActivity为启动活动,TargetActivity为目标活动。在MAInActivity中,我们创建了一个HashMap对象,并添加了两个键值对。然后,我们将HashMap转化为Bundle对象,并将Bundle对象添加到Intent中。最后,我们启动了TargetActivity。在TargetActivity中,我们通过getIntent().getExtras()方法获取传递的Intent对象,并从中提取出HashMap对象。然后,我们遍历HashMap对象,并输出其中的键值对。通过运行以上代码,我们可以在两个活动之间成功地传递HashMapCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号