Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of Object does Spinner.getItemAtPosition(...) return?

What will this statement return?

parent.getItemAtPosition(position)

Where parent is a parent view for a spinner and position is the selected position from the spinner view.

like image 576
sumit sharma Avatar asked Aug 17 '13 11:08

sumit sharma


1 Answers

I assume the "parent" you are talking about is a Spinner. In this case:

Spinner.getItemAtPosition(pos); 

will always return the type of object that you filled the Spinner with.

An example using a CustomType: (the Spinner is filled with Items of type "CustomType", therefore getItemAtPosition(...) will return CustomType)

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
CustomType [] customArray = new CustomType[] { .... your custom items here .... };

// fill an arrayadapter and set it to the spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, customArray);

spinner.setAdapter(adapter);  

CustomType type = (CustomType) spinner.getItemAtPosition(0); // it will return your CustomType so you can safely cast to it

Another example using a String Array: (the Spinner is filled with Items of type "String", therefore getItemAtPosition(...) will return String)

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
String[] stringArray= new String[] { "A", "B", "C" };

// fill an arrayadapter and set it to the spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, stringArray);

spinner.setAdapter(adapter);  

String item = (String ) spinner.getItemAtPosition(0); // it will return your String so you can safely cast to it
like image 180
Philipp Jahoda Avatar answered Dec 04 '22 09:12

Philipp Jahoda