Android 在微调器中设置键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24712540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:38:02  来源:igfitidea点击:

Set Key and Value in spinner

androidhashmapspinner

提问by Nima.S-H

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:

我有一个微调器,我想设置一个键和一个值,我使用 HashMap,它的工作,但显示一行,像这样:

enter image description here

在此处输入图片说明

Code:

代码:

        final View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

    Spinner spin=(Spinner)rootView.findViewById(R.id.spinner1);

    HashMap<Integer, String> P_Hash=new HashMap<Integer, String>();

    Update Get_Information=new Update(rootView.getContext());

    ArrayList<String> Province_NAME=new ArrayList<String>();
    Province_NAME=Get_Information.GET_Province();

    ArrayList<Integer> Province_ID=new ArrayList<Integer>();
    Province_ID=Get_Information.Get_Province_ID();

    for (int i = 0; i < Province_ID.size(); i++)
    {
        P_Hash.put(Province_ID.get(i), Province_NAME.get(i));
        Log.d("Province_ID.get(i)", Province_ID.get(i)+"");
        Log.d(" Province_NAME.get(i)",  Province_NAME.get(i)+"");
    }


    ArrayAdapter<HashMap<Integer, String>> adapter = new ArrayAdapter<HashMap<Integer,String>>(rootView.getContext(), android.R.layout.simple_spinner_item);
    adapter.add(P_Hash);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spin.setAdapter(adapter);

回答by Srinivas Guni

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

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

使用键和值填充微调器的更好方法应该是:

第 1 步:创建 POJO 类,它将处理键和值

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



注意:toString() 方法很重要,因为它负责在微调器中显示数据,您可以根据需要修改 toString()

Step 2: Prepare data to be loaded in spinner

第 2 步:准备要在微调器中加载的数据

 private void setData() {

        ArrayList<Country> 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<Country> adapter = new ArrayAdapter<Country>(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 的 onitemselected 监听器方法中获取选中项的键和值

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 !

祝您一切顺利,编码愉快!

回答by Haresh Chhelana

Try to use HashMapto store Key-Valuepair data and in your case spinner item index as keyand Province_ID as value. Check below example for more details.

尝试使用HashMap来存储键值对数据,在您的情况下,微调项索引作为键,Province_ID 作为值。查看下面的示例以获取更多详细信息。

Prepare value for spinner

为微调器准备值

String[] spinnerArray = new String[Province_ID.size()];
HashMap<Integer,String> spinnerMap = new HashMap<Integer, String>();
for (int i = 0; i < Province_ID.size(); i++)
{
   spinnerMap.put(i,Province_ID.get(i));
   spinnerArray[i] = Province_NAME.get(i);
}

Set value to spinner

将值设置为微调器

ArrayAdapter<String> adapter =new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

Get value to spinner

获取微调器的价值

String name = spinner.getSelectedItem().toString();
String id = spinnerMap.get(spinner.getSelectedItemPosition());