向下一个活动传递数据
- 在MainActivity中:
public void button1(View view){
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra("extra_data","Hello SecondActivity");
startActivity(intent);
}
- putExtra(String name,String value)中前一个参数表示The name of the extra data, with package prefix,第二个参数表示The String data value.
- 在SecondActivity中
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Intent intent=getIntent();
String data=intent.getStringExtra("extra_data");
Log.d(TAG, "onCreate: "+data);
}
getIntent()官方解释是Return the intent that started this activity
getStringExtra()中传入的参数是MainActivity中的putExtra(String name,String value)设置的name
向上一个活动返回数据
- 在MainActivity中:
public void button2(View view){
Intent intent=new Intent(this,SecondActivity.class);
startActivityForResult(intent,1);
}
public void startActivityForResult(android.content.Intent intent,int requestCode)
第一个参数传入intent,第二个参数传入请求码
- 在SecondActivity的onCreate中:
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("data_return","Hello FirstActivity");
setResult(RESULT_OK,intent);
finish();
}
});
也可以设置按返回键返回数据:
@Override
public void onBackPressed() {
Intent intent=new Intent();
intent.putExtra("data_return","Hello FirstActivity");
setResult(RESULT_OK,intent);
finish();
}
public final void setResult(int resultCode,android.content.Intent data)方法中resultCode返回码,第二个传入intent
- 在MainActivity中复写onActivityResult方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case 1:
if(resultCode==RESULT_OK){
String receiverdData=data.getStringExtra("data_return");
Toast.makeText(this,receiverdData,Toast.LENGTH_SHORT).show();
}
break;
default:
Toast.makeText(this,"nothing",Toast.LENGTH_SHORT).show();
}
}
总结:MainActivity中的startActivityForResult方法对应SecondActivity中的setResult方法。
Intent还可以传递对象,要求是对应的类实现Serializable或Parcelable接口。例子在以后章节里面用到再详解。
网友评论