Set Key and Value in spinner

前端 未结 3 1705
孤街浪徒
孤街浪徒 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:03

    Use a LinkedHashMap and store the "strings that you want to display in the spinner" as the keys and the object that you would like to retrieve based on the spinner selection as the values . For eg. , for some reason you have a Float datatype associated with the spinner items , use:

    LinkedHashMap aMap = new LinkedHashMap<>(10);
    

    Then for the spinner , we can set the values as :

        ArrayList values = new ArrayList<>(aMap.keySet());
        ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item,values);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    

    Finally , in the OnItemSelectedListener , retrieve the float value as:

     @Override
     public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
                    aMap.get(adapterView.getItemAtPosition(i));
                    
                }
    

提交回复
热议问题