1.显式跳转
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
bt1= (Button) findViewById(R.id.btn_jumptoB);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 显式
Intent intent=new Intent(AActivity.this,BActivity.class);
// Intent intent=new Intent();
intent.setAction("sankuai.com");
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);
}
}); }
2.隐式跳转
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
bt1= (Button) findViewById(R.id.btn_jumptoB);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 显式
// Intent intent=new Intent(AActivity.this,BActivity.class);
// 隐式
Intent intent=new Intent();
intent.setAction("sankuai.com");
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);
}
});
} Manifest文件中针对目标activity
<activity android:name=".jump.BActivity"
android:label="B">
<intent-filter>
<action android:name="sankuai.com" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity> 3.把数据传递到目标activity
发:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
bt1= (Button) findViewById(R.id.btn_jumptoB);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(AActivity.this,BActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);
}
}); }
收:
在目标activityz中
String name=getIntent().getStringExtra("name"); 4.返回数据给上一个活动
public void onClick(View view) {
Intent intent=new Intent(AActivity.this,BActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);--10086是requestcode
}
在目标activity中
buttonxx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent();
intent.putExtra("visitor","999999");
setResult(RESULT_OK,intent);--RESULT_OK是resultcode finish();
}
});
在BActivity被finish()销毁以后,AActivity会调用
onActivityResult方法,所以需要重写这个方法来接收来自B的传递数据
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case 10086:
if (resultCode==RESULT_OK){
String result=data.getStringExtra("visitor");
Log.d("visitor",result);
}
break;
} 总结:
startActivity只能传递给目标activity数据
startActivityForResult:既能传递数据,也能从另一个activity中回调数据给自己,如果两种都需要,可以直接使用
startActivityForResult。