问题
I have a simple application that needs to do the following:
- From the main view the user clicks a button that launches another view.
- The new view is displayed and collects information from the user.
- Once the user clicks OK on that new view I need to "send" that data back to the originating view.
The problem I am finding is that once I use StartActivity (with an intent) or SetContentView (Resource.Layout.Main) is that my data is gone. I'm putting the information I collected in a global variable but when I get back to my originating view its being recreated.
How can I pass this data back to the originating view so that I can update some UI controls?
回答1:
http://developer.android.com/training/basics/intents/result.html
Have you tried startActivityForResult. I'm guessing that is what you're looking to do.
回答2:
Something like this should work:
var activity2 = new Intent (this, typeof(Activity2));
activity2.PutExtra ("MyData", "Data from Activity1");
StartActivity (activity2);
More information about how this works here: http://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/
回答3:
You must call startActivityForResult with the intent and implement the onActivityResult for capture the info that come from Class2.
Activity Class1:
startActivityForResult(new Intent(this, Class2.class), 1);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
// do something
}
super.onActivityResult(requestCode, resultCode, data);
}
For send the info to Class1 you must call setResult with the info in your bundle and call finish().
Activity Class2:
Bundle bundle = new Bundle();
bundle.putString("---your info---");
setResult(RESULT_OK, new Intent().putExtras(bundle));
finish();
Read the section "Starting Activities and Getting Results" from http://developer.android.com/reference/android/app/Activity.html
来源:https://stackoverflow.com/questions/28464275/how-pass-data-between-two-android-views