傳遞參數的時候發現自己不太理解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;
}