What type of Object does Spinner.getItemAtPosition

2019-04-29 22:50发布

问题:

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.

回答1:

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


回答2:

It will return object of dataType you are displaying in spinner.

suppose you are displaying String array then it will return String.

if you are displaying Integer array then it will return Integer and so on.