id | title | brief | article | sdk | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9057932F-7CFB-FBF7-C558-DB8B8BEED81C |
Passing Data Between Activities |
This recipe shows how to use intents to pass data between activities. |
|
|
To pass data to an activity, follow these steps.
- Create a new Xamarin.Android application. The project template will create a single activity named
MainActivity
(MainActivity.cs), which contains a button. - Add a second activity class named
Activity2
to the project. This class must inherit fromAndroid.App.Activity
. - From the
button.Click
handler inMainActivity.cs
, create an intent forActivity2
, and add data to the intent by callingPutExtra
.
button.Click += delegate {
var activity2 = new Intent (this, typeof(Activity2));
activity2.PutExtra ("MyData", "Data from Activity1");
StartActivity (activity2);
};
- In
Activity2.OnCreate
, retrieve the data by callingIntent.GetStringExtra
.
string text = Intent.GetStringExtra ("MyData") ?? "Data not available";
Each screen in an application is represented by an activity. Sending asynchronous messages called intents, which can include data payloads, as shown in this recipe, starts activities. For more information, see the Getting Started series and the Activity Lifecycle in the Xamarin.Android documentation.