本节演示了父Activity跳转到子Activity后,接收子Activity传递回的数据。需要注意在Manifest.xml中注册子Activity。
基本步骤
1)在父Activity这边,Activity跳转时调用startActivityForResult方法,然后重写onActivityResult()方法用于接收子Activity传回的数据。
2)在子Activity这边,调用setResult()函数设置返回值。
具体解释见代码:
父Activity ReceiveResult.java:
1 public class ReceiveResult extends Activity { 2 @Override 3 protected void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 setContentView(R.layout.receive_result); 6 7 mResults = (TextView)findViewById(R.id.results); 8 9 mResults.setText(mResults.getText(), TextView.BufferType.EDITABLE); 10 Button getButton = (Button)findViewById(R.id.get); 11 getButton.setOnClickListener(mGetListener); 12 } 13 14 @Override 15 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 16 // 如果有多个子Activity都返回数据的话,可以用requestCode来区分是哪个子Activity返回的数据,但本例中只有一个Activity. 17 if (requestCode == GET_CODE) { 18 Editable text = (Editable)mResults.getText(); 19 20 // 如果子Activity启动失败或者没有传回参数,则resultCode就为RESULT_CANCELED 21 if (resultCode == RESULT_CANCELED) { 22 text.append("(cancelled)"); 23 24 // Our protocol with the sending activity is that it will send 25 // text in 'data' as its result. 26 } else { 27 text.append("(okay "); 28 text.append(Integer.toString(resultCode)); 29 text.append(") "); 30 if (data != null) { 31 text.append(data.getAction()); 32 } 33 } 34 text.append("\n"); 35 } 36 } 37 38 static final private int GET_CODE = 0; 39 40 private OnClickListener mGetListener = new OnClickListener() { 41 public void onClick(View v) { 42 // 若需获取子Activity传递回来的数值,此处就不再是调用startActivity()函数了,而是调用startActivityForResult()函数, 43 // 参数GET_CODE用来区分是哪个子Activity传回的数据。需要重写onActivityResult()函数。 44 Intent intent = new Intent(ReceiveResult.this, SendResult.class); 45 startActivityForResult(intent, GET_CODE); 46 } 47 }; 48 49 private TextView mResults; 50 }
子Activity ReceiveResult.java
1 public class SendResult extends Activity 2 { 3 protected void onCreate(Bundle savedInstanceState) 4 { 5 super.onCreate(savedInstanceState); 6 7 setContentView(R.layout.send_result); 8 9 Button button = (Button)findViewById(R.id.corky); 10 button.setOnClickListener(mCorkyListener); 11 button = (Button)findViewById(R.id.violet); 12 button.setOnClickListener(mVioletListener); 13 } 14 15 private OnClickListener mCorkyListener = new OnClickListener() 16 { 17 public void onClick(View v) 18 { 19 // 在Activity finish之前,调用setResult函数,确定本activity返回的值 20 21 setResult(RESULT_OK, (new Intent()).setAction("Corky!")); 22 finish(); 23 } 24 }; 25 26 private OnClickListener mVioletListener = new OnClickListener() 27 { 28 public void onClick(View v) 29 { 30 // To send a result, simply call setResult() before your 31 // activity is finished. 32 setResult(RESULT_OK, (new Intent()).setAction("Violet!")); 33 finish(); 34 } 35 }; 36 }
布局文件比较简单,就不放出了,以上即可。
下一节: