Bundle传递数据,Handler更新UI

Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的。

Bundle经常使用在Activity之间或者线程间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。

当Bundle传递的是对象或对象数组时,必须实现Serializable 或Parcelable接口。

Bundle提供了各种常用类型的putXxx()/getXxx()方法,用于读写基本类型的数据。(各种方法可以查看API)

在activity间传递信息

Intent intent  = new Intent(mContext,DetailActivity.class);
Bundle bundle = new Bundle();

bundle.putCharSequence("newsId",newsId);           
bundle.putString("sff", "value值");  //key-"sff",通过key得到value-"value值"(String型)  
bundle.putInt("iff", 175);  //key-"iff",value-175  

intent.putExtras(bundle); //通过intent将bundle传到另个Activity   
startActivity(intent);

接收数据

 //接收Intent发过来的数据
 Intent intent  = getIntent();
 Bundle bundle = intent.getExtras();
 String newsId = bundle.getString("newsId");

线程间传递

通过Handler将带有dundle数据的message放入消息队列,其他线程就可以从队列中得到数据

Message message=new Message();//new一个Message对象 
message.what = MESSAGE_WHAT_2;//给消息做标记 
Bundle bundle = new Bundle(); //得到Bundle对象 
bundle.putString("text1","消息传递参数的例子!"); //往Bundle中存放数据 
bundle.putInt("text2",44); //往Bundle中put数据 
message.setData(bundle);//mes利用Bundle传递数据 
mHandler.sendMessage(message);//Handler将消息放入消息队列 

读取数据
这里用的是Handler的handleMessage(Message msg)方法处理数据

String str1=msg.getData().getString("text1"); 
int int1=msg.getData().getString("text2");

转自:https://blog.csdn.net/yiranruyuan/article/details/78049219

猜你喜欢

转载自www.cnblogs.com/xuqp/p/9817580.html
今日推荐