資源描述:
《在兩個(gè)activity間傳值》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、一、android開(kāi)發(fā)之在activity中控制另一個(gè)activity的UI更新1.在MyAPP中定義屬性handler[java]viewplaincopyprint?1packagejason.com;23importjason.com.MasterActivity.MyHandler;4importandroid.app.Application;56/**7*自己實(shí)現(xiàn)Application,實(shí)現(xiàn)數(shù)據(jù)共享8*@authorjason9*/10publicclassMyAPPextendsApplication{11//共享變量12privat
2、eMyHandlerhandler=null;1314//set方法15publicvoidsetHandler(MyHandlerhandler){16this.handler=handler;17}1819//get方法20publicMyHandlergetHandler(){21returnhandler;22}2324}2、在主activity中給MyAPP的屬性handler賦值[java]viewplaincopyprint?25@Override26publicvoidonCreate(BundlesavedInstanceSta
3、te){2728super.onCreate(savedInstanceState);29setContentView(R.layout.main);30311mAPP=(MyAPP)getApplication();2handler=newMyHandler();3tv=(TextView)findViewById(R.id.tv);4btn_to=(Button)findViewById(R.id.btn_to);56//設(shè)置監(jiān)聽(tīng)器7btn_to.setOnClickListener(newOnClickListener(){8@Overri
4、de9publicvoidonClick(Viewv){10//設(shè)置共享變量11mAPP.setHandler(handler);12//啟動(dòng)另一個(gè)Activity13Intentintent=newIntent(MasterActivity.this,14ToChangeViewActivity.class);15startActivity(intent);16}17});1819}3、在另一個(gè)activity中獲取MyAPP中handler進(jìn)行傳值[java]viewplaincopyprint?20protectedvoidonCreate
5、(BundlesavedInstanceState){21super.onCreate(savedInstanceState);22setContentView(R.layout.show);2324mAPP=(MyAPP)getApplication();25//獲得該共享變量實(shí)例26mHandler=mAPP.getHandler();27findViewById(R.id.btn_chang).setOnClickListener(newOnClickListener(){2829@Override30publicvoidonClick(V
6、iewv){31//發(fā)送消息32mHandler.sendEmptyMessage(CHANGED);33ToChangeViewActivity.this.finish();34}35});3637}二、android開(kāi)發(fā)之如何在兩個(gè)activity之間傳遞handler_利用broadcast廣播機(jī)制其實(shí)很簡(jiǎn)單,就是Broadcast的應(yīng)用,替換了原來(lái)想要通過(guò)共享handler解決的思路。代碼如下:MainActivity:[java]viewplaincopyprint?1packagejason.broadcastinsteadofhan
7、lderdemo;23importandroid.app.Activity;4importandroid.content.BroadcastReceiver;5importandroid.content.Context;6importandroid.content.Intent;7importandroid.content.IntentFilter;8importandroid.os.Bundle;9importandroid.view.View;10importandroid.view.View.OnClickListener;11import
8、android.widget.Button;12importandroid.widget.TextView;1314publicclas