Bundle的作用,以及和Intent的區別:
一、Bundle: A mapping from String values to various Parcelable types
鍵值對的集合
類繼承關系:
java.lang.Object
android.os.Bundle
Bundle類是一個final類:
public final class Bundle extends Objectimplements Parcelable Cloneable
作用:可以用作是兩個Activity間的通訊。
用法:
①、裝載數據:
Bundle mBundle = new Bundle();
mBundle.putString( "DataTag" , "要傳過去的數據" );
Intent intent = new Intent();
intent.setClass(MainActivity.this, Destion.class);
intent.putExtras(mBundle);
②、目標Activity解析數據
Bundle bundle = getIntent().getExtras(); //得到傳過來的bundle
String data = bundle.getString( "DataTag" ); //讀出數據
二、Intent的含義和作用 就略了。。。直接上二者比較:
兩個Activity之間傳遞數據,數據的附加有兩種方式:
一種是直接 intent.putxx();
另一種是 先bundle.putxx(), 然后再調用public Intent putExtras (Bundle extras) 添加bundle.
其實兩種的本質是一樣的。
先看Intent的方法:
public Intent putExtra(String name, boolean value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putBoolean(name, value);
return this;
}
其中mExtras是intent內部定義的一個private Bundle變量。
可以看到,intent其實是調用了bundle相應的put函數,也就是說,intent內部還是用bundle來實現數據傳遞的,只是封裝了一層而已。
而使用Bundle傳值的話最后調用的方法:Intent.putExtras(Bundle extras):
public Intent putExtras(Bundle extras) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putAll(extras);
return this;
}
可以看到,其實是把之前那個bundle中的數據批量添加到intent內部的bundle中。
其實是和上面的直接用Intent傳鍵值對是一樣的原理。
總之呢,Intent旨在數據傳遞,bundle旨在存取數據,當然intent也提供一部分數據的存取,但比起bundle就顯得不專業,不靈活的多
