5

我正在创建一个简单的应用程序来熟悉 Xamarin。我想创建和填充微调器并动态显示其选项。我在这里看到了文档,但它不是以编程方式创建的。任何帮助将不胜感激

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();
};

我的 axml 文件

<?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>
4

1 回答 1

20

要为其动态创建项目Spinner,您需要有一个适配器

最简单的适配器是ArrayAdapter<T>.

这是示例。

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

设置好后,在您的视图中adapter找到并设置它。Spinneradapter

var spinner = FindViewById<Spinner>(Resource.Id.spinner);
spinner.Adapter = adapter;
于 2013-10-03T19:26:17.450 回答