資源描述:
《在兩個activity間傳值》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、一、android開發(fā)之在activity中控制另一個activity的UI更新1.在MyAPP中定義屬性handler[java]viewplaincopyprint?1packagejason.com;23importjason.com.MasterActivity.MyHandler;4importandroid.app.Application;56/**7*自己實現(xiàn)Application,實現(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//設置監(jiān)聽器7btn_to.setOnClickListener(newOnClickListener(){8@Overri
4、de9publicvoidonClick(Viewv){10//設置共享變量11mAPP.setHandler(handler);12//啟動另一個Activity13Intentintent=newIntent(MasterActivity.this,14ToChangeViewActivity.class);15startActivity(intent);16}17});1819}3、在另一個activity中獲取MyAPP中handler進行傳值[java]viewplaincopyprint?20protectedvoidonCreate
5、(BundlesavedInstanceState){21super.onCreate(savedInstanceState);22setContentView(R.layout.show);2324mAPP=(MyAPP)getApplication();25//獲得該共享變量實例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開發(fā)之如何在兩個activity之間傳遞handler_利用broadcast廣播機制其實很簡單,就是Broadcast的應用,替換了原來想要通過共享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