Android-如何在微调器中获取所有项目? [英] Android - How to get all items in a Spinner?

查看:60
本文介绍了Android-如何在微调器中获取所有项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在微调框中获取所有项目?

How do I get all items in a Spinner?

我在尝试寻找一种方法来获取 Spinner 中的所有物品时遇到了麻烦,但是我找不到一个优雅的解决方案.唯一的解决方案似乎是先存储项目列表,然后再将其添加到 Spinner

I was having trouble trying to search a way to get all items from a Spinnerbut I was not able to find an elegant solution. The only solution seems to be storing the items list before to add it to the Spinner

还有另一种更好的方法吗?

Is there another better way to do this?

推荐答案

一种简单而优雅的方法是,如果您知道微调器要存储的对象类型:

A simple and elegant way to do this is, if you know the objects type that the spinner is storing:

public class User {

    private Integer id;

    private String name;

    /** Getters and Setters **/

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

给定上一类和一个 Spinner (其中包含 User 的列表),您可以执行以下操作:

Given the previous class and a Spinner that contains a list of User you can do the following:

public List<User> retrieveAllItems(Spinner theSpinner) {
    Adapter adapter = theSpinner.getAdapter();
    int n = adapter.getCount();
    List<User> users = new ArrayList<User>(n);
    for (int i = 0; i < n; i++) {
        User user = (User) adapter.getItem(i);
        users.add(user);
    }
    return users;
}

这对我有帮助!我希望它能为您做到!

This helped me! I hope it would do it for you!

这篇关于Android-如何在微调器中获取所有项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆