Spinner的SelectedItem始终为null

时间:2018-03-15 14:20:27

标签: android xamarin xamarin.android spinner

我为我的微调器控件创建了自定义数组适配器,但是当单击列表中的项目时,它未被选中。这是我的代码:

public class CustomArrayAdapter : BaseAdapter
{
    readonly LayoutInflater inflater;
    List<string> items;

    public CustomArrayAdapter(Context context, List<string> items)
    {
        this.inflater = LayoutInflater.FromContext(context);
        this.items = items;
    }

    public override int Count
    {
        get { return items.Count; }
    }

    public override Object GetItem(int position)
    {
        return null;
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var view = convertView ?? inflater.Inflate(Resource.Layout.SpinnerItem, parent, false);
        var item = items[position];
        view.FindViewById<TextView>(Resource.Id.spinnerItem).Text = item;
        return view;
    }
}

旋转器布局:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerItem"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="@color/background_color"
android:textSize="25dp"
android:gravity="center_vertical"
android:textAlignment="center" />

我是如何使用适配器的:

CustomArrayAdapter adapter = new CustomArrayAdapter(this, spinnerItems.ToList());
spinnerLoginName.Adapter = adapter;

1 个答案:

答案 0 :(得分:3)

您需要从GetItem方法中的列表中返回值而不是null

public override Object GetItem(int position)
    {
        return items.get(position);
    }