简体   繁体   中英

How to set selected item of Spinner by value, not by position

<item value="245">Guinea-Bissau [245]</item >
<item value="592">Guyana [592]</item >
<item value="509">Haiti  [509]</item >
<item value="504">Honduras [504]</item >
<item value="91">India [91]</item >
<item value="62">Indonesia [62]</item >

I am using this

country.setOnItemSelectedListener(new OnItemSelectedListener() {

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        // TODO Auto-generated method stub
        //selectioncountry = parent.getItemAtPosition(position).toString();
        selectionarea = parent.getItemIdAtPosition(position);
    }

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

        // TODO Auto-generated method stub          
    }
});

this code give thie value of india is 4 but i need 91 how can i do this ???

private void selectSpinnerValue(Spinner spinner, String myString)
     {
         int index = 0;
         for(int i = 0; i < spinner.getCount(); i++){
             if(spinner.getItemAtPosition(i).toString().equals(myString)){
                 spinner.setSelection(i);
                 break;
             }
         }
     }

try this. it will work fine.

int position = adapter.getPosition(value);
spinner.setSelection(position);

You have to take one more string array for selected country respective value :

<string-array name="country">
   <item>India</item>
</string-array>

<string-array name="country_value">
  <item>91</item>
</string-array>

Initialize value array :

String[] countryValue = getResources().getStringArray(R.array.country_value);

Get spinner selected item respective value from value array:

selectionarea = countryValue[position];

Check Example : accessing item name in string-array (Android)

for(int i = 0; i < country.getCount(); i++){
    if(country.getItemAtPosition(i).toString().equals("yourString")){
        country.setSelection(i);
        break;
    }
}

You could also solve it by this way, by specifiying the String you are searching for instead if you have access to it. Otherwise, you will have to follow Haresh Chhelana's approach.

您始终可以覆盖getItemId(int position)以返回值,而不是默认的位置ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM