我正在开发Xamarin Android。我创建了自己的自定义Spinner
,其中包含Image
和TextView
。在我的活动中,我需要获取Spinner当前所选项目的值,但我得到System.InvalidCastException: Specified cast is not valid.
我的代码如下:
CustomSpinner.axml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/splash_background"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@drawable/thinking_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:id="@+id/FeedTypeImage" />
<TextView
android:text="Thinking of"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Black"
android:id="@+id/FeedTypeText"
android:layout_marginLeft="10dp" />
CustomSpinnerAdapter.cs
public class CustomSpinnerAdapter : BaseAdapter
{
private Context c;
private JavaList<FeedType> feedTypes;
private LayoutInflater inflater;
public CustomSpinnerAdapter(Context c, JavaList<FeedType> feedTypes)
{
this.c = c;
this.feedTypes = feedTypes;
}
public override int Count
{
get { return feedTypes.Size(); }
}
//compiler throws InvalidCast Exception here
public override Object GetItem(int position)
{
return feedTypes.Get(position);
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
if (inflater == null)
inflater = (LayoutInflater)c.GetSystemService(Context.LayoutInflaterService);
if (convertView == null)
convertView = inflater.Inflate(Resource.Layout.CustomSpinner, parent, false);
TextView feedTitle = convertView.FindViewById<TextView>(Resource.Id.FeedTypeText);
ImageView feedImage = convertView.FindViewById<ImageView>(Resource.Id.FeedTypeImage);
feedTitle.Text = feedTypes[position].Title;
feedImage.SetImageResource(feedTypes[position].FeedTypeImage);
return convertView;
}
}
MyActivity.cs
private Spinner spinnerPostType;
spinnerPostType = FindViewById<Spinner>(Resource.Id.spinner);
spinnerAdapter = new CustomSpinnerAdapter(this, feedType);
spinnerPostType.Adapter = spinnerAdapter;
string selectedSpinnerText = spinnerPostType.SelectedItem.ToString();
答案 0 :(得分:0)
而不是覆盖GetItem
方法尝试覆盖索引器
public override FeedType this[int position] {
get {
return feedTypes.Get(position);
}
}
答案 1 :(得分:0)
试试这个:
//Get the selected position in your spinner
int position = spinnerPostType.SelectedItemPostition;
//Get the title of the selected item
string selectedSpinnerText = feedType[position].Title;
我希望这会有所帮助:)