Set Key and Value in spinner

前端 未结 3 1707
孤街浪徒
孤街浪徒 2020-11-27 12:13

I have a spiner and I want set a key and a value on this,I use of HashMap,It\'s work,but show one row,like this:

3条回答
  •  佛祖请我去吃肉
    2020-11-27 13:04

    Better approach to populate spinner with key and value should be :

    Step 1 : Create POJO class which will take care of key and value

    public class Country {
    
        private String id;
        private String name;
    
        public Country(String id, String name) {
            this.id = id;
            this.name = name;
        }
    
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    
        //to display object as a string in spinner
        @Override
        public String toString() {
            return name;
        }
    
        @Override
        public boolean equals(Object obj) {
            if(obj instanceof Country){
                Country c = (Country )obj;
                if(c.getName().equals(name) && c.getId()==id ) return true;
            }
    
            return false;
        }
    
    }
    



    Note : toString() method is important as it is responsible for displaying the data in spinner,you can modify toString() as per your need

    Step 2 : Prepare data to be loaded in spinner

     private void setData() {
    
            ArrayList countryList = new ArrayList<>();
            //Add countries
    
            countryList.add(new Country("1", "India"));
            countryList.add(new Country("2", "USA"));
            countryList.add(new Country("3", "China"));
            countryList.add(new Country("4", "UK"));
    
            //fill data in spinner 
            ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, countryList);
            spinner_country.setAdapter(adapter);
            spinner_country.setSelection(adapter.getPosition(myItem));//Optional to set the selected item.    
        }
    


    Step 3 : and finally get selected item's key and value in onitemselected listener method of spinner

    spinner_country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView parent, View view, int position, long id) {
    
                     Country country = (Country) parent.getSelectedItem();
                     Toast.makeText(context, "Country ID: "+country.getId()+",  Country Name : "+country.getName(), Toast.LENGTH_SHORT).show();    
                }
    
                @Override
                public void onNothingSelected(AdapterView parent) {    
                }
            });
    


    All the best , Happy coding !

提交回复
热议问题