开发者

pass argument to previous activity

开发者 https://www.devze.com 2023-02-18 01:59 出处:网络
I would like to pass arguments from an activity B to A where B h开发者_如何学编程as been launched by A. Is this possible to do so ?

I would like to pass arguments from an activity B to A where B h开发者_如何学编程as been launched by A. Is this possible to do so ? Thanks


Yes, if when you launch Activity B from A, you start it using startActivityForResult then you can set a result in Activity B then read the value in A.

In A you would need to override onActivityResult to get the result value.

In Activity B:

// do stuff
setResult(RESULT_OK);
finish();

Then in A:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    //check result
}


To expand a bit on davec's answer:

If you need more data than just RESULT_OK, then you will have to use putExtra() in B and getExtras() in A. You can send primitive data types, e.g for String:

In B:

String str1 = "Some Result";
Intent data = new Intent();
data.putExtra("myStringData", str1);
setResult(RESULT_OK, data); 

Then to pick it up in A:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);

   if (resultCode == RESULT_OK) {
      if (data != null) {
         Bundle b = data.getExtras(); 
         String str = b.getString("myStringData");
      }
   }
}    

.


Look at startActivityForResult (to be called from A), setResult (to be called from B), and onActivityResult (A's callback that gets called after B exits).

0

精彩评论

暂无评论...
验证码 换一张
取 消