Reputation: 15553
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?
Upvotes: 3
Views: 9133
Reputation: 1111
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
}
});
Upvotes: 2
Reputation: 3874
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>
Upvotes: 0