Create android spinner dynamically in Xamarin

佐手、 提交于 2020-01-13 02:44:09

问题


I'm a newbie to Xamarin and I want to create a simple application to get familiar with Xamarin. I want to create and populate the spinner and display it's options dynamically. I have seen the documentation here but it is not created programmatically. Any help will be apreaciated

var levels = new List<String>() { "Easy", "Medium", "Hard", "Multiplayer" };
var adapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleSpinnerItem, levels);
                    adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
var spinner = FindViewById<Spinner>(Resource.Id.spnrGameLevel);
spinner.Adapter = adapter;

spinner.ItemSelected += (sender, e) =>
{
    var s = sender as Spinner;
    Toast.MakeText(this, "My favorite is " + s.GetItemAtPosition(e.Position), ToastLength.Short).Show();
};

My axml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Choose your game level" />
    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spnrGameLevel" />
</LinearLayout>

回答1:


To dynamically create items for Spinner, you need to have an adapter.

The simplest adapter would be ArrayAdapter<T>.

Here is the example.

var items = new List<string>() {"one", "two", "three"};
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);

After setting up the adapter, find the Spinner in your view and set adapter to it.

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


来源:https://stackoverflow.com/questions/19165260/create-android-spinner-dynamically-in-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!