如何在Android下拉列表中添加键

时间:2018-07-18 13:18:49

标签: android android-layout android-fragments

我需要将country代码传递到服务器,并向用户显示完整的国家/地区名称。

例如:USA用于服务器,United State of America用于显示。

这就是我现在正在使用的。

<string-array name="countries_array">
        <item>United State of America</item>
</string-array>

但是现在我需要显示country full name,但将其code传递给服务器。

这就是我要获得所选值的方法。

spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
                               int position, long id) {
        country = spinnerCountry.getSelectedItem().toString();

3 个答案:

答案 0 :(得分:1)

是OOPS。
您可以使用具有国家/地区代码和全名的类,然后使用其列表通过国家/地区代码(由用户选择)来获得coutry的全名。

具有两个大小和顺序相同的国家/地区代码及其全名的不同数组。

答案 1 :(得分:1)

您甚至不需要写所有国家名称和国家代码。您可以从Android语言环境中获取它们。尝试以下代码。

  String[] isoCountryCodes = Locale.getISOCountries();
        ArrayList<Country> countryArrayList = new ArrayList<Country>();

        for (String code : isoCountryCodes) {
            Locale locale = new Locale("", code);
            String name = locale.getDisplayCountry();
            countryArrayList.add(new Country(name, code));
        }
        //Sort Country List
        Collections.sort(countryArrayList, new Comparator<Country>() {
            @Override
            public int compare(Country c1, Country c2) {
                return c1.countryName.compareTo(c2.countryName);
            }
        });

        Spinner spinnerCountry = (Spinner) findViewById(R.id.spinnerCountry);
        ArrayAdapter<Country> arrayAdapter = new ArrayAdapter<Country>(this, android.R.layout.simple_spinner_item, countryArrayList);
        spinnerCountry.setAdapter(arrayAdapter);
        spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String countryCode = countryArrayList.get(i).countryCode;
                Toast.makeText(TestActivity.this, countryCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

并按照以下步骤创建国家/地区类

class Country {
    String countryName;
    String countryCode;

    public Country(String countryName, String countryCode) {
        this.countryName = countryName;
        this.countryCode = countryCode;
    }

    @Override
    public String toString() {
        return countryName ;
    }
}

答案 2 :(得分:0)

您可以尝试使用country-picker-android

您具有由ISO国家/地区代码引用的标志图标/完整的国家/地区名称,并且可以在用户选择时获取该国家/地区的ISO代码。