如何向Spinner添加项目?

时间:2015-04-14 04:59:17

标签: android xamarin xamarin.android

这就是我现在正在做的事情

Spinner AddressTypeSpinner = FindViewById<Spinner>(Resource.Id.spinner1);


ArrayAdapter spinnerArrayAdapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem, new ProfileAddressTypes[] 
{ 

    for (var i = 0; i < AddressObject.Count; i++) 
    {
        new ProfileAddressTypes (AddressObject[i].id, AddressObject[i].name); 
    }
});

AddressTypeSpinner.Adapter = spinnerArrayAdapter;

这不起作用,它说无法放入数组适配器

我不知道如何做到这一点任何人都有任何想法?

4 个答案:

答案 0 :(得分:0)

试试这个:

ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,mArrayListspinner);
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        AddressTypeSpinner.setAdapter(spinnerArrayAdapter);

此处 mArrayListspinner 是您的字符串数组。

答案 1 :(得分:0)

ProfileAddressTypes[] mList = new ProfileAddressTypes[size];

for (int i = 0; i < size; i++) {
   mList[i]= new ProfileAddressTypes (AddressObject[i].id, AddressObject[i].name);        
}

ArrayAdapter spinnerArrayAdapter = new ArrayAdapter (this, R.id_from_your_layout_of_that_activity_or_fragment, mList);  
yourSpinner.setAdapter(spinnerArrayAdapter ); 

希望有所帮助:)

答案 2 :(得分:0)

ArrayAdapter spinnerArrayAdapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem, GetAdapterData());

public ProfileAddressTypes[] GetAdapterData()
{
    var adapterData = new ProfileAddressTypes[AddressObject.Count];

    for (var i = 0; i < AddressObject.Count; i++) 
    {
        adapterData[i] = new ProfileAddressTypes (AddressObject[i].id, AddressObject[i].name); 
    }
    return adapterData;
}

或者使用List<T>代替并在结尾处调用ToArray()

 public ProfileAddressTypes[] GetAdapterData()
 {
      var adapterData = new List<ProfileAddressTypes>();

      for (var i = 0; i < AddressObject.Count; i++) 
      {
          adapterData.Add(new ProfileAddressTypes (AddressObject[i].id, AddressObject[i].name)); 
      }
      return adapterData.ToArray();
 }

答案 3 :(得分:0)

您必须传入ArrayAdapter构造函数而不是数组,而是传递实现接口IList的对象,例如List<ProfileAddressTypes>,除了正确的输出之外,您应该覆盖方法ToString()。< / p>

这是我的代码:

Spinner modelSelect = FindViewById<Spinner>(Resource.Id.modelSelect);
List<Marks> models = (from i in DBHelper.GetInstance().Table<Marks>() where i.removed == false orderby i.name ascending select i).ToList();
modelSelect.Adapter = new ArrayAdapter<Marks>(this, Android.Resource.Layout.SimpleSpinnerItem, models);

课程Models的一部分:

public override string ToString()
{
    return name;
}