重溫 Activity Intent 如何向下傳遞數(shù)據(jù) 向上傳遞數(shù)據(jù)
1、使用Intent向下傳遞數(shù)據(jù)
Intent?intent?=?new?Intent(MainActivity.this,SecongActivity.class); intent.putExtra("data_from_MainActivity","I?am?MainActivity"); startActivity(intent);
從SecondActivity取數(shù)據(jù)
Intent?intent?=?getIntent(); String?data?=?intent.getStringExtra("data_from_MainActivity");
根據(jù)傳遞的數(shù)據(jù)的類型選擇getIntExtra()/getBooleanExtra...
2、向上傳遞數(shù)據(jù)
MainActivity.java
Intent?intent1?=?new?Intent("sunny.example.comeonintent.ACTION"); startActivityForResult(intent1,1);
期望返回數(shù)據(jù)
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中接收數(shù)據(jù)
@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: } }