1.activity之间的跳转和传递数据
1)启动另一个activity,使用Intent,首先创建需要启动的activity,如BActivity(如手动创建需要在AndroidManifest.xml中添加注册):
<activity
android:name=".BActivity" >
</activity>
2)启动方法
显式意图:
Intent intent1 = new Intent(this, BActivity.class);
startActivity(intent1);
隐式意图:
Intent intent2 = new Intent();
intent2.setAction("com.ql.BActivity");
startActivity(intent2);
这时需要在AndroidManifest.xml中设置BActivity的action标签name值和category值
<activity
android:name="com.ql.activatyintentdemo.BActivity"
android:label="@string/title_activity_b" >
<intent-filter>
<actionandroid:name="com.ql.BActivity" />
<categoryandroid:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
3)四种传值方式
①Intent
发送端:直接用Intent对象加值
intent.putExtra("msg","我是Intent传过来的。。。");
接收端:
Intentintent = getIntent();
Stringmsg = intent.getStringExtra("msg");
参数"msg"—>key值,可以定义为常量。
②Applecation
仍然需要Intent启动另一个activity,只是使用Application进行对值的保存
定义MyApplication继承Application,如
public class MyApplecationextends Application {
privateString msg;
publicString getMsg() {
returnmsg;
}
publicvoid setMsg(String msg) {
this.msg= msg;
}
}
传值端:设置对象和数据
MyApplecation applecation =(MyApplecation) getApplication();
applecation.setMsg("我是Applecation传过来的。。。。");
接收端:
MyApplecation applecation =(MyApplecation) getApplication();
String msg= applecation.getMsg();
③Bundle
同样需要Intent启动另一个activity,数据则使用Bundle包裹
Intentintent4 = new Intent();
Bundle bundle = new Bundle();
bundle.putString("key1","Bundle_v1");
bundle.putString("key2","Bundle_v2");
bundle.putString("key3","Bundle_v3");
intent4.putExtra("key_bundle",bundle);
接收端:
Intent intent = getIntent();
Bundlebundle = intent.getBundleExtra("key_bundle");
Stringv1 = bundle.get("key1").toString();
Stringv2 = bundle.get("key2").toString();
Stringv3 = bundle.get("key3").toString();
参数key必须要一样。
④startActivityForResult()
这个方法可以进行双向传值,如:
Mainactivity中:
Intent intent = newIntent(this, BActivity.class);
startActivityForResult(intent,REQ_CODE_GET_NAME_AGE); ---->第二个参数是请求码,如果有不同activity都访问这个资源时,如果不指定则不指定是谁在访问
然后重写方法onActivityResult(int requestCode, int resultCode, Intent data),
参数:requestCode请求码,resultCode返回码,data 返回的数据
@Override
protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode, data);
switch(requestCode) {
caseREQ_CODE_GET_NAME_AGE:
if(resultCode== Activity.RESULT_OK){
Stringname = data.getStringExtra(BActivity.KEY_NAME);
Stringnum = data.getStringExtra(BActivity.KEY_NUM);
}
break;
}
}
BActivity中:
Intent data = new Intent();
data.putExtra(KEY_NAME,value);
data.putExtra(KEY_NUM, value);
setResult(Activity.RESULT_OK,data);
参数:value需要传的值,setResult(intresultCode, Intent data),resultCode返回码,data 返回的数据
2.Activity的生命周期
1) 七大生命周期方法
onCreate:资源的初始化
onStart:程序启动
onResume:可交互
onPause:保存当前状态
onStop:停止
onRestart:重新启动
onDestroy:销毁资源