Android 微调器:获取选定的自定义对象

Android Spinner: Get selected custom object

在这个简单的示例中,我将向您展示我通常如何获取微调器的选定项目,其中填充了来自自定义 class 的项目。

// Simple sample class
public class StringWithIndex
{
    public string itemString;
    public int itemIndex;

    public StringWithIndex(string stringPart, int indexPart)
    {
        itemString = stringPart;
        itemIndex = indexPart;
    }

    public override string ToString()
    {
        return itemString;
    }
}

// Create sample list
List<StringWithIndex> spinnerItems = new List<StringWithIndex>();
spinnerItems.Add(new StringWithIndex("A", 1));
spinnerItems.Add(new StringWithIndex("B", 2));
spinnerItems.Add(new StringWithIndex("C", 3));

// Create Spinner
Spinner spinner = new Spinner(Context);
var spinnerAdapter = new ArrayAdapter<StringWithIndex>(Context, Android.Resource.Layout.SimpleSpinnerItem, spinnerItems);
spinner.Adapter = spinnerAdapter;

// Spinner Item selected
 spinner.ItemSelected += (sender, e) =>
{
    var pos = spinner.SelectedItemPosition;
    var item = spinnerItems[pos];
    // do something with item
};

我知道所选项目的位置并在用于所选项目的适配器的列表中搜索。

所以我的问题是,有没有办法直接访问对象,而无需在原始列表中搜索? 例如,所选项目的演员表不起作用

var itemString = (spinner.SelectedItem as StringWithIndex).itemString;

我现在不知道在没有列表的情况下访问项目的好处,但每次我实现微调器时我都会问自己这个问题。

编辑: 我的想法是使用 SelectedItem。我知道有很多方法可以在任何类型的传递列表或来自适配器的覆盖方法中使用该位置。

你不是在搜索,当你选择项目时,你是在获取项目的位置,当你有位置时,你可以从列表中的某个位置获取项目

val adapter = ArrayAdapter(context, R.layout.your_custom__header_layout,
                   yourModels)

            adapter.setDropDownViewResource(R.layout.costom_layout_of_item
            spinner.adapter = adapter


spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>, view: View,
                                            position: Int, id: Long) {
                    val stringWithIndex = parent.getItemAtPosition(position) as StringWithIndex
                }

                override fun onNothingSelected(parent: AdapterView<*>) {
                    // Empty
                }
            }

So my question is, is there a way to access the object directly, without searching in the original list?

你可以试试这个:

Spinner spinner = new Spinner(Context);
var spinnerAdapter = new ArrayAdapter<StringWithIndex>(Context, Android.Resource.Layout.SimpleSpinnerItem, spinnerItems);
spinner.Adapter = spinnerAdapter;

// Spinner Item selected
spinner.ItemSelected += (sender, e) =>
  {        
    var obj = e.Parent.SelectedItem;
    var item = obj.GetType().GetProperty("Instance").GetValue(obj) as StringWithIndex;
    var itemString = item .itemString;
  }