java - 在没有 hashmap 结构的微调器中使用键和值

标签 java android hashmap spinner

我有键和值的列表, key = 是表中的 id 字符串。 value = 是一个名称字符串,

我想在微调器 View 中仅显示没有 ID 的值,但是在用户单击某个项目后,我需要获取所选项目的 Id,并在代码中使用它。 如何在不使用 hashMap 或许多 foreach 语句的情况下实现此结构?

谢谢,

最佳答案

创建一个 POJO 类并将自定义对象的 ArrayList 传递给微调器。

class MyClass{
    private String id;
    private String key;

    public MyClass(String id, String value) {
        this.id = id;
        this.value = value;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    } 

    @Override
    public String toString() {
        return value;
    }   
}

重写toString()方法很重要。这就是微调器项目中将显示的内容。

您可以将其传递给您的ArrayAdapter,如下所示:

ArrayAdapter userAdapter = new ArrayAdapter(this, R.layout.spinner, myList);

当用户单击某个项目时,getSelectedItem() 方法将为您提供对象。您可以从那里获取 id

来自docs :

A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

关于java - 在没有 hashmap 结构的微调器中使用键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069692/

相关文章:

java - 空安全 boolean 表达式评估

java - 如何修复 Scanner 类接受额外的空白输入

java - 替换所有出现的组

java - 如何使用正则表达式检查密码是否包含字母和数字

android - 通过选择在 Compose 中仅突出显示一张卡片

android - 如何在 Android 中打开任何扩展名的文件?

Android Studio - GitHub Push 无法正常工作

java - Java中HashMap解析并访问以下JSON数据格式

hashmap - VacantEntry 未在名为 set 的范围内实现任何方法

hashmap - 具有动态键值 HashMap 的 Swagger 复杂响应模型