Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Spinner value?

People also ask

How do I get the value from spinner in Kotlin?

This example demonstrates how to get Spinner value in Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

Which function is used to get the selected item from the spinner?

When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. The AdapterView. OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods. Spinner spinner = (Spinner) findViewById(R.


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

The Spinner should fire an "OnItemSelected" event when something is selected:

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) {
    }
});

Say this is your xml with spinner entries (ie. titles) and values:

<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>

and this is your spinner:

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

Then in your code to get the entries:

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

and to get the values:

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

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.


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

If you already know the item is a String, I prefer:

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

Calling toString() on an Object that you know is a String seems like a more roundabout path than just casting the Object to String.