As in the title -
Is there any way to determine the type of the item (typically either a String
, if adapted from a resource, or a generic Object
, if adapted programmatically) obtained from a Spinner in onItemSelected
? In this case, I'm referring to one filled programmatically in Java, but as far as I know, it would be the same for one created from a String resource array.
Obviously, however, we create our Spinner, we know what type everything in it is. If it's from resources, probably Strings. If done programmatically, some kind of Object
or possibly View
. However, the signature for onItemSelected
looks like this:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// actions
// to get the item, you would usually do something like:
parent.getItemAtPosition(pos);
}
And obviously, the type we get from this is ?
, in other words, a generic Object
.
So, if we know exactly what type it is, we can, of course, do this (example shown with an Integer
):
Object itemSelected = parent.getItemAtPosition(pos);
if (itemSelected instanceof Integer) doSomeMath((Integer) itemSelected);
But this doesn't exactly strike me as elegant. It works, certainly, at least in the simple cases I've given it (like Integer
). It might even be useful for handling multiple different types of Spinner
all running off the same listener
- I haven't actually tried that.
But it seems like there should be a way to have the signature simply be something like:
public void onItemSelected(AdapterView<Integer> parent, View view, int pos, long id)