Android spinner showing object reference instead of string

后端 未结 4 1424
耶瑟儿~
耶瑟儿~ 2021-01-04 01:52

Ok so I am having a issue with my spinner. Its being populated with data pulled from a webservice. The issue im having is that when the spinner is not clicked instead of sho

4条回答
  •  囚心锁ツ
    2021-01-04 02:33

    I was having a similar issue, however I was using the default ArrayAdapter without extending it in a separate class. After looking into it a little bit, I found this:

    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.

    The default ArrayAdapter will call .toString() on each object in the array that has been passed to the Adapter. If your DrinkAdapter does nothing more than display the name of the Drink, you can override the toString() method and be finished

    Adapter:

    ArrayAdapter drinkAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_dropdown_item, drinks);
    

    Class Object:

    public Drink {
    
        String name;
    
        // Constructor, getters, and setters for the object here
    
        @Override
        public String toString() {
            return getName(); // You can add anything else like maybe getDrinkType()
        }
    }
    

    And you're done, no need to make a separate class for your DrinkAdapter

提交回复
热议问题