Introduction
In this article, we will see how to data from one activity to another using Intent in Xamarin. In my previous article, we learned about
the Checkbox widget in Xamarin.
Let's begin.
1. Create a new Android Application in Visual Studio / Xamarin.
2. Add a layout (named Main.axml).
3. Drop a TextView, EditText(set id="@+id/txt_Name") and Button(set id="@+id/btn_Submit" and text="Submit") control onto the Main.axml Layout.
4. Add another Layout and name it Result.axml.
Drop a TextView (Large) control onto the Result.axml Layout and set id="@+id/txt_Result".
Activity1.cs Code
- using System;
-
- using Android.App;
- using Android.Content;
- using Android.Widget;
- using Android.OS;
-
- namespace IntentDemo
- {
- [Activity(Label = "IntentDemo", MainLauncher = true, Icon = "@drawable/icon")]
- public class Activity1 : Activity
- {
- EditText txt_Name;
- Button btn_Submit;
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
-
- SetContentView(Resource.Layout.Main);
-
- txt_Name = FindViewById<EditText>(Resource.Id.txt_Name);
- btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit);
-
- btn_Submit.Click += btn_Submit_Click;
- }
-
- void btn_Submit_Click(object sender, EventArgs e)
- {
-
- if(txt_Name.Text!="")
- {
-
- Intent i = new Intent(this,typeof(Activity2));
-
- i.PutExtra("Name",txt_Name.Text.ToString());
-
- StartActivity(i);
- }
- else
- {
- Toast.MakeText(this,"Please Provide Name",ToastLength.Short).Show();
- }
- }
- }
- }
In the preceding code, we have created an Intent and bound the Activity2 to it. The PutExtra method of Intent allows us to store data in Key-Value pairs. We can retrieve the data in the other Activity using the Intent.GetTypeExtra method. In the preceding code, we have ed a string using a PutExtra() method and for retrieving the string in the other activity (in other words Activity2), we use the Intent.GetStringExtra("Name") method and a key/value pair in it as a parameter.
Activity2.cs Code
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Widget;
-
- namespace IntentDemo
- {
- [Activity(Label = "Result")]
- public class Activity2 : Activity
- {
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
-
- SetContentView(Resource.Layout.Result);
-
- TextView txt_Result = FindViewById<TextView>(Resource.Id.txt_Result);
-
- string name = Intent.GetStringExtra("Name");
- txt_Result.Text ="Hello, "+name;
- }
- }
- }
Final Preview
I hope you like it. Thanks.