[英]How to get the ID of selected item in a spinner?
I've a Spinner, with following values/properties. 我有一个Spinner,具有以下值/属性。
<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
. 从代码级别,我正在使用以下代码来获取所选
item
的ID
。
final long spinID= ((Spinner)findViewById(R.id.spin)).getSelectedItemId();
If I select Two, I'm getting 0
instead of 2
. 如果我选择2,则得到
0
而不是2
。
Why? 为什么?
Implement an setOnItemSelectedListener
. 实现
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. 确保项目标签支持id属性。 I m finding problems here.
我在这里发现问题。 Its returning its row_id in the spinner.
它在微调器中返回其row_id。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.