9
I started fiddling around with MonoDroid this week. Not that I don't appreciate Java, but I spend most of my time in either Visual Studio / C# or Delphi, and I'd rather pull my fingernails out than learn YET ANOTHER IDE and YET ANOTHER editor in order to use Eclipse.
I adapted this code to C# from Java, for situations where it's easier to populate my spinner programmatically in C# code rather than in the AXML. Perhaps some of you may find it helpful.
Create a generic Spinner In Your Activity's axml:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_prompt"
/>
Build your array of string somewhere appropriate:
public static readonly string[] refresh_ratesS = {"10 seconds","20 seconds","30 seconds","60 seconds","5 minutes"};
I prefer to instantiate objects in the Activity's public class so that I only have to identify them once:
public class ActivityChooseRefreshRate :Activity {
Spinner jb_spinner;
In the Activity's OnCreate function assign your array to the spinner:
//identify the spinner
jb_spinner = FindViewById<Spinner>(Resource.Id.spinner);
//create the handler for when the user selects something
jb_spinner.ItemSelected += new EventHandler<ItemEventArgs> (jb_spinner_ItemSelected);
//assign your array to an ArrayAdapter
ArrayAdapter<string> spinnerArrayAdapter = new ArrayAdapter<string>(this,Android.Resource.Layout.SimpleSpinnerItem,refresh_ratesS);
//Use the ArrayAdapter you've set up to populate your spinner
spinnerArrayAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerItem);
jb_spinner.Adapter = spinnerArrayAdapter;
//optionally pre-set jb_spinner to an index
jb_spinner.SetSelection(2);
Lastly, code the