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
android:entries
made my day.
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
.
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();
Success story sharing