一、从一个Activity启动另一个Activity
1.建立Activity
public class IntentOneDemoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_itone);
}
}
public class IntentTwoDemoActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_ittwo);
}
}
2.从IntentOneDemoActivity 启动IntentTwoDemoActivity
Intent it=new Intent(IntentOneDemoActivity.this,IntentTwoDemoActivity.class);
IntentOneDemoActivity.this.startActivity(it);
从IntentTwoDemoActivity
返回IntentOneDemoActivity
IntentTwoDemoActivity.this.finish();
二、从一个Activity传值到另一个Activity
1.设置值,启动IntentTwoDemoActivity
Intent it=new Intent(IntentOneDemoActivity.this,IntentTwoDemoActivity.class);
it.putExtra("username", "zhangsan");
IntentOneDemoActivity.this.startActivity(it);
2.在IntentTwoDemoActivity中接受
Intent it=IntentTwoDemoActivity.this.getIntent();
String name=it.getStringExtra("username");
Toast.makeText(IntentTwoDemoActivity.this, name, Toast.LENGTH_SHORT).show();
三、 从IntentOneDemoActivity中接受IntentTwoDemoActivity的返回值**
1.启动IntentTwoDemoActivity
Intent it=new Intent(IntentOneDemoActivity.this,IntentTwoDemoActivity.class);
//it.putExtra("username", "zhangsan");
//IntentOneDemoActivity.this.startActivity(it);
IntentOneDemoActivity.this.startActivityForResult(it, 1);
2.IntentTwoDemoActivity设置返回值
Intent retIt=IntentTwoDemoActivity.this.getIntent();
retIt.putExtra("retMsg", "lisi");
//一定要有这句,设置返回结果。 IntentTwoDemoActivity.this.setResult(Activity.RESULT_OK, retIt);
IntentTwoDemoActivity.this.finish();
3.IntentOneDemoActivity中接受返回值
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case Activity.RESULT_OK:
String retMsg=data.getStringExtra("retMsg");
Toast.makeText(IntentOneDemoActivity.this, retMsg, Toast.LENGTH_SHORT).show();
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
网友评论