如何获得Spinner值?

时间:2009-12-22 17:30:08

标签: android spinner

在Android中,我试图通过监听器获取所选的Spinner值。

获得微调器值的最佳方法是什么?

7 个答案:

答案 0 :(得分:527)

Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();

答案 1 :(得分:121)

当选择某些内容时,Spinner应该触发“OnItemSelected”事件:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Object item = parent.getItemAtPosition(pos);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

答案 2 :(得分:44)

假设这是带有微调条目(即标题)和值的xml:

<resources>
    <string-array name="size_entries">
        <item>Small</item>
        <item>Medium</item>
        <item>Large</item>
    </string-array>

    <string-array name="size_values">
        <item>12</item>
        <item>16</item>
        <item>20</item>
    </string-array>
</resources>

这是你的微调器:

<Spinner
    android:id="@+id/size_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/size_entries" />

然后在您的代码中获取条目:

Spinner spinner = (Spinner) findViewById(R.id.size_spinner);
String size = spinner.getSelectedItem().toString(); // Small, Medium, Large

并获取值:

int spinner_pos = spinner.getSelectedItemPosition();
String[] size_values = getResources().getStringArray(R.array.size_values);
int size = Integer.valueOf(size_values[spinner_pos]); // 12, 16, 20

答案 3 :(得分:12)

是的,您可以通过setOnItemSelectedListener()注册听众,如演示here

答案 4 :(得分:11)

View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();

答案 5 :(得分:10)

如果您已经知道该项目是String,我更喜欢:

String itemText = (String) mySpinner.getSelectedItem();

在您知道toString()的{​​{1}}上呼叫Object似乎是一个更加迂回的路径,而不仅仅是将String转换为Object

答案 6 :(得分:2)

将setOnItemSelectedListener添加到微调器参考并获得类似的数据`

 mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            selectedSize=adapterView.getItemAtPosition(position).toString();