How to Bind Array List into Spinner in Android App using C#

In this tutorial, I will show you how to bind array list into spinner in android apps using c sharp with Xamarin. Spinner is a widget similar to a drop-down list.



Follow these steps to display an array of string in a spinner.

  • Create new Project
  • Expand resource folder
  • Click on layout folder  
  • Open  layout  Main.axml and paste below code


<?xml version=1.0 encoding=utf-8?>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
    android:orientation=vertical
    android:padding=10dip
    android:layout_width=fill_parent
    android:layout_height=wrap_content>
    <TextView
        android:layout_width=fill_parent
        android:layout_height=wrap_content
        android:layout_marginTop=10dip
        android:text=@string/spinner1 />
    <Spinner
        android:layout_width=match_parent
        android:layout_height=61.0dp
        android:id=@+id/spinner1 />
</LinearLayout>

Open MainActivity.cs
In MainActivity create  ItemSelected event .overriding ItemSelected allows us to handle item selection.

MainActivity.cs

 public class MainActivity : Activity
    {
        private  List<string>Mlist;
        private Spinner spinner;
        protected override voidOnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the “main” layout resource
            SetContentView (Resource.Layout.Main);
            Mlist = new List<string>();
            Mlist.Add(“Sunday”);
            Mlist.Add(“Monday”);
            Mlist.Add(“Tuesday”);
            Mlist.Add(“Wednesday”);
            Mlist.Add(“Thursday”);
            Mlist.Add(“Friday”);
            Mlist.Add(“Saturday”);
            spinner = FindViewById<Spinner>(Resource.Id.spinner1);
            ArrayAdapter adapter =new  ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem,Mlist);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;
            spinner.ItemSelected += spinner_Click;           
                     
        }
        private voidspinner_Click(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Toast.MakeText(this, “Selected Day  “ + spinner.GetItemAtPosition(e.Position), ToastLength.Short).Show();
        }
    }
}



4 Comments on “How to Bind Array List into Spinner in Android App using C#”

Leave a Reply

Your email address will not be published. Required fields are marked *