Reputation: 6188
I have created a Spinner and ArrayAdapter as follows:
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.units_array1, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
The units_array1 is a string array declared in a xml file like this:
<string-array name="units_array1">
<item>Centimeters</item>
<item>Meters</item>
<item>Kilometers</item>
<item>Inches</item>
<item>Foots</item>
<item>Miles</item>
</string-array>
Now I want to implement some If-ELSE conditions that are based on the elements in string-array. I Have researched a lot on the internet for this but haven't found out any solution that works. Please help me in implementing a function that returns the individual elements from the string-array using the adapter.
Upvotes: 0
Views: 3595
Reputation: 5183
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String scale = adapter1.getItem(position);
// scale is gonna be "Centimeters" or "Meters", etc...
if (scale.equals("Centimeters")) {
// do something
} else if (scale.equals("Meters")) {
// do something else
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Upvotes: 2
Reputation: 28418
You need to set a OnItemSelectedListener
to your spinner. Then in the listener you'll be notified about the selection event. Check the official sample on this: Spinner.
Upvotes: 1
Reputation: 63303
ArrayAdapter.getItem(position)
, where position is the index into the array. If you want to get the currently selected item in your Spinner, use Spinner.getSelectedItemPosition()
as the parameter to getItem()
.
This will return a CharSequence
because of you your adapter is typed. If you want that values to return as Strings, redefined your adapter as ArrayAdapter<String>
HTH!
Upvotes: 3
Reputation: 10938
ArrayAdapter has getItem(int position), which (if you know the position) will get you the String. ArrayAdapter also has getCount(), so you can write a simple for loop to get each element if you don't know its position.
Upvotes: 1