how to set default value of the spinnerlist

2019-09-16 18:02发布

问题:

In Android I am fetching json data from web.I the list is like {Name,dial,code}

I have this

countryinfo = new ArrayList<CountryInfo>();
        Countrylist = new ArrayList<String>();
            try {           
                for (String line : result) {
                jsonarray= new JSONArray(line);
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);
                CountryInfo conpop = new CountryInfo();
                conpop.setName(jsonobject.optString("Name"));
                conpop.setIso(jsonobject.optString("dial"));
                conpop.setItu(jsonobject.optString("code"));
                countryinfo.add(conpop);
                Countrylist.add(jsonobject.optString("Name"));
                }
                }
        } catch (Exception e) {
            //Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

I use

Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);

             ArrayAdapter<String> adapter = new ArrayAdapter<String>(MobnoAct.this, android.R.layout.simple_spinner_item, Countrylist);  
                            mySpinner.setAdapter(adapter); 
              mySpinner.setSelection(0);

But in the spinner Its showing a default country name..But I want The country name will be as per locale.. like :--

Locale defaultLocale = getResources().getConfiguration().locale;
               String si=defaultLocale.getCountry();

How I can do that???

回答1:

Try this after you set the adapter and retrieve the default local:

 for(String countryName : countryList)
            for(CountryInfo country : countryinfo)
                if(country.getName().equals(countryName) && country.getCode().toLowerCase().equals(si.toLowerCase()))
                    mySpinner.setSelection(adapter.getPosition(countryName));

Hope this helps