传递参数的时候发现自己不太理解Bundle,在此记录一下方便查阅.
Class Overview
java.lang.Object | |
↳ | android.os.Bundle |
Bundle: A mapping from String values to various Parcelable types. ---------------->map类型的<key value>对。
java.lang.Object | |
↳ | android.content.Intent |
Bundle |
getBundle(
String key)
Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.
|
Intent |
putExtra(
String name,
Bundle value)
Add extended data to the intent.
|
Intent |
putExtra(
String name,
String value)
Add extended data to the intent.
|
Bundle |
getExtras()
Retrieves a map of extended data from the intent.
|
intent当中有个返回Bundle的方法。
这里就拿示例的方法来演示看看传递参数的问题
发送参数的activity部分代码:
Intent intent = new Intent(MainActivity.this,Target.class);
intent.putExtra("2", "2");
startActivity(intent);
接受参数的activity部分代码:
Intent intent = getIntent();
String value = intent.getStringExtra("2");
Log.d("see2", value);
logcat输出的结果:
01-13 00:46:10.021: D/see2(2397): 2
从结果就能看出,存入的参数能被第二个activity取出,那么问题来了。在多放几个是否可以都取出来呢?用代码来看看是否可以
发送参数的activity部分代码:
Intent intent = new Intent(MainActivity.this,Target.class);
intent.putExtra("2", "2");
intent.putExtra("1", "1");
startActivity(intent);
接受参数的activity部分代码:
Intent intent = getIntent();
String value = intent.getStringExtra("2");
String value1 = intent.getStringExtra("1");
Log.d("see1", value1);
Log.d("see2", value);
logcat输出的结果:
01-13 00:43:11.051: D/see1(2283): 1
01-13 00:43:11.051: D/see2(2283): 2
嗯,表明没有问题,存入多少就能拿出多少,那么尝试Bundle传递参数看看。
发送参数的activity部分代码,以Bundle的形式发送:
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String b1 = bundle.getString("b1");
String b2 = bundle.getString("b2");
String bc1 = bundle.getString("bc1");
String bc2 = bundle.getString("bc2");
Log.d("see1", b1);
Log.d("see1", b2);
Log.d("see1", bc1);
Log.d("see1", bc2);
接收参数的activity部分代码,以Bundle的形式发送:
Bundle bundle = new Bundle();
Bundle bundleCopy = new Bundle();
bundle.putString("b1", "b1toTag");
bundle.putString("b2", "b2toTag");
bundleCopy.putString("bc1", "bc1toTag");
bundleCopy.putString("bc2", "bc2toTag");
Intent intent = new Intent(MainActivity.this,Target.class);
intent.putExtras(bundle);
intent.putExtras(bundleCopy);
startActivity(intent);
logcat输出的结果:
01-13 00:22:41.721: D/see1(2215): b1toTag
01-13 00:22:41.721: D/see1(2215): b2toTag
01-13 00:22:41.721: D/see1(2215): bc1toTag
01-13 00:22:41.721: D/see1(2215): bc2toTag
你要是直接放入Intent当中,也会帮你实例出一个Bundle的对象的。
源码的说明如下
public Intent putExtra(String name, boolean value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putBoolean(name, value);
return this;
}