简体   繁体   中英

How to get the ID of selected item in a spinner?

I've a Spinner, with following values/properties.

<Spinner
    android:id="@+id/spin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:entries="@array/spin_ent"
    android:prompt="@string/spin_prompt" />

<string-array name="spin_ent">
    <item id="2">Two</item>
    <item id="1">One</item>
    <item id="3">Three</item>
    <item id="4">Four</item>
    <item id="5">Five</item>
</string-array>

From code level, I'm using the below code to get the ID of selected item .

final long spinID= ((Spinner)findViewById(R.id.spin)).getSelectedItemId();

If I select Two, I'm getting 0 instead of 2 .

Why?

Implement an setOnItemSelectedListener . Check the code below to help you understand better.

int count;
spinner1 = (Spinner) findViewById(R.id.spin);

spinner1 .setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                spinner1 = parent.getItemAtPosition(position).toString();
                count = position; //this would give you the id of the selected item
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

Ru sure item tag supports id attribute. I m finding problems here. Its returning its row_id in the spinner.

<string-array name="spin_ent">
 <item id="2">Two</item>
 <item id="1">One</item>
 <item id="3">Three</item>
 <item id="4">Four</item>
 <item id="5">Five</item>
</string-array>

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