Android - How to get all items in a Spinner?

后端 未结 1 436
孤城傲影
孤城傲影 2021-01-02 12:43

How do I get all items in a 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 so

1条回答
  •  抹茶落季
    2021-01-02 13:47

    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;
        }
    }
    

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

    public List retrieveAllItems(Spinner theSpinner) {
        Adapter adapter = theSpinner.getAdapter();
        int n = adapter.getCount();
        List users = new ArrayList(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!

    0 讨论(0)
提交回复
热议问题