Intent本身就可以傳遞參數(shù)(Intent.putExtra("key", value))為何還要用Bundle呢?
兩者比較
- Bundle只是一個(gè)信息的載體,內(nèi)部其實(shí)就是維護(hù)了一個(gè)Map<String,Object>。
- Intent負(fù)責(zé)Activity之間的交互,內(nèi)部是持有一個(gè)Bundle的。
- putExtra()方法的源碼
public Intent putExtra(String name, boolean value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putBoolean(name, value);
return this;
}
- putExtras(Bundle bundle):會(huì)將Intent的內(nèi)部Bundle替換成參數(shù)bundle。
應(yīng)用場(chǎng)景
例1:
從A界面跳轉(zhuǎn)到B界面或者C界面
這樣的話 我就需要寫2個(gè)Intent 如果你還要涉及的傳值的話 你的Intent就要寫兩遍添加值的方法。那么,如果我用1個(gè)Bundle,直接先存值,然后再存到Intent中 不就更簡(jiǎn)潔嗎?例2:
現(xiàn)在要把值通過Activity A經(jīng)過Activity B傳給Activity C。
如果用Intent的話,A-B先寫一遍,再在B中都取出來 然后在把值塞到Intent中,再跳到C。
如果在A中用了 Bundle 的話,把Bundle傳給B,在B中再轉(zhuǎn)傳到C,C就可以直接去取了。
bundle使用場(chǎng)景
- 在設(shè)備旋轉(zhuǎn)時(shí)保存數(shù)據(jù)
// 自定義View旋轉(zhuǎn)時(shí)保存數(shù)據(jù)
public class CustomView extends View {
@Override
protected Parcelable onSaveInstanceState() {
super.onSaveInstanceState();
Bundle bundle = new Bundle();
bundle.put...
return bundle;
}
// Activity旋轉(zhuǎn)時(shí)保存數(shù)據(jù)
public class CustomActivity extends Activity {
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.put...
}
- Fragment之間傳遞數(shù)據(jù)
比如,某個(gè)Fragment中點(diǎn)擊按鈕彈出一個(gè)DialogFragment。
最便捷的方式就是通過Fragment.setArguments(args)傳遞參數(shù)。
所以,Bundle是不可替代的。