В этой статье вы узнаете, как передавать данные из одного действия в другое с помощью Intent в Xamarin. В моей предыдущей статье мы узнали о виджете Checkbox в Xamarin .
Давайте начнем:
1. Создайте новое приложение для Android.
2. Добавьте макет (названный Main.axml).
3) Перетащите TextView, EditText (set id = «@ + id / txt_Name») и Button (set id = «@ + id / btn_Submit» и text = «Submit») в макет Main.axml.
4) Добавьте другой макет и назовите его Result.axml.
Удалите TextView (Large) элемент управления в макете Result.axml и установите id = «@ + id / txt_Result».
Код Activity1.cs:
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);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
//Get txt_Name and btn_Submit Button CheckBox control from the Main.xaml Layout.
txt_Name = FindViewById<EditText>(Resource.Id.txt_Name);
btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit);
//btn_Submit click event
btn_Submit.Click += btn_Submit_Click;
}
void btn_Submit_Click(object sender, EventArgs e)
{
//if EditText in not Empty
if(txt_Name.Text!="")
{
//passing the Activity2 in Intent
Intent i = new Intent(this,typeof(Activity2));
//Add PutExtra method data to intent.
i.PutExtra("Name",txt_Name.Text.ToString());
//StartActivity
StartActivity(i);
}
else
{
Toast.MakeText(this,"Please Provide Name",ToastLength.Short).Show();
}
}
}
}
В приведенном выше коде мы создали намерение и привязали к нему действие 2. Метод Intent PutExtra позволяет нам хранить данные в парах ключ-значение. Мы можем получить данные в другой Деятельности, используя Намерение. Метод GetTypeExtra. В приведенном выше коде мы передали строку с использованием метода PutExtra (), а для извлечения строки из другого действия мы используем метод Intent.GetStringExtra («Name») и передаем в него значение ключа в качестве параметра.
Код Activity2.cs:
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);
// Set our view from the "Result" layout resource
SetContentView(Resource.Layout.Result);
//Get txt_Result TextView control from the Main.xaml Layout.
TextView txt_Result = FindViewById<TextView>(Resource.Id.txt_Result);
//Retrieve the data using Intent.GetStringExtra method
string name = Intent.GetStringExtra("Name");
txt_Result.Text ="Hello, "+name;
}
}
}
Окончательный просмотр:
Надеюсь, вам понравится. Спасибо.





