我刚开始探索Spinner控件。我已经实现了我想要的东西但只缺少最后一步。这是我到目前为止所做的。
这个例子我有一个非常简单的类:
[Serializable]
public class Merchant
{
public Int64 MerchantId { get; set; }
public String ShopName { get; set; }
public override string ToString()
{
return ShopName;
}
}
这是我放置Spinner的轴:
<?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'
。
请告诉我如何实现。
感谢。
答案 0 :(得分:0)
微调器只知道文本,因为这是你ToString()
方法中的内容。提供微调器数据的适配器不知道它正在处理Merchant
个对象。
要访问实际的商家对象,您必须让List<Merchant> lstMerchant
成为您班级的成员。
然后更改您的选择处理程序:
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
// Get the ID from your model.
Merchant merch = this.lstMerchant[e.Position];
var id = merch.MerchantId;
string toast = string.Format ("Selected text is {0}", spinner.GetItemAtPosition (e.Position));
Toast.MakeText (this, toast, ToastLength.Long).Show ();
}