Search code examples
c#oopxamarinxamarin.android

How to add an element to a spinner, Xamarin Android?


I am building an android application with Xamarin.Android which used to be a Windows CE app. I have this little piece of code that is supposed to loop through an array from a different project class and add the items to the checkbox i.e spinner in Xamarin. Do you know how to do this the best way in Xamarin? Thanks.

     docTypes = CommonData.ListDocTypes("E|");
        docTypes.Items.ForEach(dt =>
        {
            cbDocType.Items.Add(new ComboBoxItem { ID = dt.GetString("Code"), Text = dt.GetString("Code") + " " + dt.GetString("Name") });
        });

Solution

  • By using ArrayAdapter as said in microsoft docs.

    These are the two steps.

    1. Create the adapter object

      var adapter = ArrayAdapter.CreateFromResource ( this, YOUR DATA, Android.Resource.Layout.SimpleSpinnerItem);

      adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);

    2. Assign it to spinner

      spinner.Adapter = adapter;

    https://learn.microsoft.com/en-us/xamarin/android/user-interface/controls/spinner