Search code examples
xamarinandroid-activityxamarin.formsspinnermenuitem

How can I open another activity using spinner item selection in xamarin.forms only?


I've tried this and it looks like majority of search results reference to Android studio. I'm using visual studio, xamarin forms.

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);

    SetContentView (Resource.Layout.Main);

    Spinner spinner = FindViewById<Spinner> (Resource.Id.spinner);

    spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);
    var adapter = ArrayAdapter.CreateFromResource (
            this, Resource.Array.my_array, Android.Resource.Layout.SimpleSpinnerItem);

    adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
    spinner.Adapter = adapter;
}

The spinner loads perfectly but the item selected method opens the activity on loading.

private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
 SetContentView (Resource.Layout.page1);
}

How best can I load the activity on specific item selection. Note: the items are referenced in the Strings.xml.


Solution

  • Because Spinner chooses the first item by default when initialized, it will fire spinner_ItemSelected

    You can add a conditional judgment to your spinner_ItemSelected method:

    private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
     {
        var index = e.Parent.SelectedItemPosition; //base on the select position
        var obj = e.Parent.SelectedItem; // base on the selectitem value(string) 
        // xxx is your conditions
        if(index == xxx)
         {
          SetContentView (Resource.Layout.page1);
         }
        // or 
        if(obj.ToString().Equals("xxx"))
         {
          SetContentView (Resource.Layout.page1);
         }
     }