Reputation: 1
I want to select an item in the spinner and then write it in a TextView
but I have an error.
Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner);
TextView mytext = FindViewById<TextView>(Resource.Id.textView1);
List<string> dataList = new List<string>();
dataList.Add("2");
dataList.Add("1");
dataList.Add("3");
var ArrayAdapter1 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, dataList);
spinner.Adapter = ArrayAdapter1;
if (spinner.SelectedItem.Equals("2"))
mytext.Text = "click 2";
if (spinner.SelectedItem.Equals("1"))
mytext.Text = "click 1";
Upvotes: 0
Views: 217
Reputation: 9356
You need to subscribe to the ItemSelected
event and there validate for the item that was selected.
Try this:
spinner.ItemSelected += (sender, e) => {
var itemSelected = (string) spinner.SelectedItem;
if (itemSelected == "1")
{
textView.Text = "Clicked 1";
}
else if (itemSelected == "2")
{
textView.Text = "Clicked 2";
}
};
UPDATE
To use is inside a button click event handler method you just need to:
Make both your textView and your spinner a private field in the class, so it can be accessed from another place is your code and add this code below inside your method:
var itemSelected = (string) spinner.SelectedItem;
if (itemSelected == "1")
{
textView.Text = "Clicked 1";
}
else if (itemSelected == "2")
{
textView.Text = "Clicked 2";
}
Hope this helps.-
Upvotes: 3