我刚刚开始探索 Spinner 控件。我几乎已经实现了我想要的,但只缺少最后一步。这是我到目前为止所做的。
对于这个例子,我有一个非常简单的类:
[Serializable]
public class Merchant
{
public Int64 MerchantId { get; set; }
public String ShopName { get; set; }
public override string ToString()
{
return ShopName;
}
}
这是我放置 Spinner 的 axml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="1280dip"
android:layout_height="800dip">
<TextView
android:text="Select a merchant:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/lblSelect"
android:layout_marginLeft="30dip"
android:layout_marginTop="30dip"
android:textSize="42dip" />
<Spinner
android:id="@+id/spinMerchant"
android:layout_width="1000dip"
android:layout_height="wrap_content"
android:layout_below="@id/lblSelect"
android:prompt="@string/spinner_prompt"
android:layout_centerHorizontal="true"
android:minHeight="20dip" />
</RelativeLayout>
我的代码是:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create your application here
this.SetContentView(Resource.Layout.MerchantSelect);
List<Merchant> lstMerchant = new List<Merchant> ();
lstMerchant.Add (new Merchant() { ShopName = "First Shop", MerchantId = 11 });
lstMerchant.Add (new Merchant() { ShopName = "Second Shop", MerchantId = 12 });
Spinner spinner = this.FindViewById<Spinner>(Resource.Id.spinMerchant);
ArrayAdapter adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem, lstMerchant);
spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);
spinner.Adapter = adapter;
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
//Merchant merch = (Merchant)spinner.SelectedItem;
string toast = string.Format ("Selected text is {0}", spinner.GetItemAtPosition (e.Position));
Toast.MakeText (this, toast, ToastLength.Long).Show ();
}
做出选择后,我想立即获取所选文本及其背后的 ID。我得到了文本,spinner.GetItemAtPosition (e.Position)
但我似乎找不到任何可以给我 ID 的东西。如果我尝试这样做,Merchant merch = (Merchant)spinner.SelectedItem;
我会得到一个例外:Cannot convert type 'Java.Lang.Object' to 'Merchant'
.
请让我知道如何实现。
谢谢。