将自定义对象设置为 Spinner 并显示特定 属性

Setting a custom object to a Spinner and showing a specific property

我有一个微调器,我需要用字符串值填充它,但我还需要保存该字符串的 ID。

我要在微调器中显示这个结构

public class Item{

    private Integer id;

    private Double name;
}

我想在微调器中显示名字,但是当我 select 一个项目并按下一个按钮时,我想要那个名字的 ID。

字符串不重复,所以我可以做一个 Map<Integer, String> 来管理它,但我想知道是否存在更好的解决方案,比如自定义适配器或微调器的布局或为微调器设置一种数据源对象并显示对象的特定 属性。

这是我的spinner_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinnerTarget"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="12pt"
    android:gravity="center"/>

在您的 class Item 中设置 toString() 覆盖: 例子

@Override
public String toString() {
    return getName(); // You can add anything else like maybe getDrinkType()
}

layouts/layout_spinner:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textColor="#000000"
    android:textAlignment="center"
    />

在你的javaclass:

public void loadSpin(List<Item> itemList)
{
     ArrayAdapter<Item> adapter =
                new ArrayAdapter<Item>(YourActivity.this, R.layout.layout_spinner, itemList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        yourSpinner.setSelection(0);
        yourSpinner.setAdapter(adapter);
}

像这样更改模型class

public class Item{

private String id;
private String name;

 public String getId() {
    return id;
}

public String getName() {
    return name;
}

public String toString() {
return getName();
}

}

像这样设置微调器适配器

ArrayAdapter<Item> adapter =
                        new ArrayAdapter<Item>(getActivity(), android.R.layout.simple_spinner_dropdown_item, dataNew);
spinner.setAdapter(adapter);

现在获取所选项目的 ID,

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
          //get id of the selected item using position 'i'
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });