1、使用Intent向下传递数据
Intent intent = new Intent(MainActivity.this,SecongActivity.class);
intent.putExtra("data_from_MainActivity","I am MainActivity");
startActivity(intent);
从SecondActivity取数据
Intent intent = getIntent();
String data = intent.getStringExtra("data_from_MainActivity");
根据传递的数据的类型选择getIntExtra()/getBooleanExtra...
2、向上传递数据
MainActivity.java
Intent intent1 = new Intent("sunny.example.comeonintent.ACTION");
startActivityForResult(intent1,1);
期望返回数据
startActivityForResult()
void android.support.v4.app.FragmentActivity.startActivityForResult(Intent intent, int requestCode)
SubActivity.java
Intent intent = new Intent();
intent.putExtra("data_from_sub", "I am Sub");
setResult(RESULT_OK,intent);//RESULT_OK -1;RESULT_CANCELED 0;
在MainActivity中接收数据
<span style="white-space:pre"> </span>@Override
protected void onActivityResult(int RequestCode,int ResultCode,Intent data){
TextView tv1 = (TextView)findViewById(R.id.tv1);
TextView tv2 = (TextView)findViewById(R.id.tv2);
switch(RequestCode){
case 1:
if(ResultCode == RESULT_OK){
String returnData1 = data.getStringExtra("data_from_sub");
tv1.setText(returnData1);
}else{}
case 2:
if(ResultCode == RESULT_OK){
String returnData2 = data.getStringExtra("data_from_third");
tv2.setText(returnData2);
}else{
}
default:
}
}
完整代码在:https://github.com/HiSunny/ComeOnIntent.git