在 Android 中使用自定义适配器设置 Spinner 的值

Set value for Spinner with custom Adapter in Android

我正在开发一个 android 应用程序,其中包含表单中的微调器。 微调器项目和微调器值不同。我想从包括微调器在内的微调器中收集所有值,并为 Web 后端设置一个休息 api 服务。

这里是响应数组。

{"Status":true,"errorType":null,"countryList":[{"Code":"US","Name":"United States"},{"Code":"CA","Name":"Canada"},{"Code":"AU","Name":"Australia"},{"Code":"GB","Name":"United Kingdom"}]}

我已成功将 Name jsonObject 绑定到微调器,但我无法添加 Code.

这是我的代码。

JSONObject responseObject = new JSONObject(res);
            String status=responseObject.getString("Status");
            JSONArray JA = responseObject.getJSONArray("countryList");
            JSONObject json= null;


            if(status.equals("true")) {

                final String[] str2 = new String[JA.length()];
                for (int i=0;i<JA.length();i++)
                {
                    json = JA.getJSONObject(i);
                    str2[i] = json.getString("Name");
                }

                sp = (Spinner) findViewById(R.id.citnzshp_field);
                list = new ArrayList<String>();

                for(int i=0;i<str2.length;i++)
                {
                    list.add(str2[i]);

                }
                Collections.sort(list);

                ArrayAdapter<String> adp;
                adp = new ArrayAdapter<String>
                        (getApplicationContext(),android.R.layout.simple_dropdown_item_1line, list);

                sp.setAdapter(adp);


            }

如何将 code jsonObject 绑定到微调器以便在表单提交后获取。

任何人都可以分享我制作自定义适配器以将数据绑定到微调器并选择值的优势。

@Haresh Chhelana 的例子很好,但是如果你想在选择后在微调器中同时显示名称和代码,请检查这个。

    List<Map<String, String>> items = new ArrayList<Map<String, String>>();

    for (int i = 0; i < JA.length(); i++) {
        json = JA.getJSONObject(i);
        mapData = new HashMap<String, String>();
        mapData.put("name", json.getString("Name"));
        mapData.put("code", json.getString("Code"));
        items.add(mapData);
    }

    SimpleAdapter adapter = new SimpleAdapter(this, items, android.R.layout.simple_list_item_2, new String[] {
            "name", "code" }, new int[] { android.R.id.text1, android.R.id.text2 });
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

和Spinner选择项回调

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Map<String, String> selectedItem = (Map<String, String>) parent.getSelectedItem();
                String name=selectedItem.get("name");
                String code=selectedItem.get("code");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });