bundle是在android中十分有用的一种类,我们通常用它来进行参数的传递。理解bundle可以把它当作一个Map<String,?>,所以它的本质是一个key-value键值对。其中key值为一个标识参数的String值,value即为该String对应的参数。
使用bundle传递参数会在intent、message、fragment中用到,下面就总结一下这几种情况下用bundle封装参数以及取出参数的写法。
1.intent(两个Activity的信使)使用bundle传递参数:
发送:
Bundle bundle = new Bundle();
bundle.putString("name" , "Lily");
bundle.putDouble("score" , 89.7);
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setClass(ThisOne.this , ThatOne.class);
startActivity(intent);
接收:
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
double score = bundle.getDouble("score");
或者发送:
intent.putExtra("date", selectDate);
接收:
Intent.getExtras().getString("date")
2.message(常常跟handler结合使用)使用bundle传递参数:
使用Message机制主要是为了保证线程之间操作安全,同时不需要关心具体的消息接收者,使消息本身和线程剥离开,这样就可以方便的实现定时、异步等操作。
发送:
Message msg = new Message();
msg.what = 0x123;
Bundle b = new Bundle();
b.putInt("age" , 20);
b.putString("name" , "Lily");
msg.setData(b);
接收:
Handler myHandler = new Handler{
public void handleMessage(Message msg){
Bundle b = msg.getData();
int age = b.getInt("age");
String name = b.getString("name");
}
}
3.在Fragment(Activity片段)中使用Bundle传递参数
发送:
Bundle args = new Bundle();
args.putInt("","");
args.putString("","");
frament.setArguments(key, int);
接收:
Bundle args = getArguments();
String data = args.getInt(key);
String str = args.getString(key);