Reputation: 303
I want a spinner to return an value to me once the user has selected an item.
I know I could use a button and then use spinner.getSelectedItemPosition() in the OnClick(), but I want the value to be returned as soon as the user has selected amongst the spinner choices. Thus, I had thought to use an OnItemSelectedListener.
int valueINeed;
subGoalSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
//I now want to somehow get the value of the index for use outside of this code block
}
I can obviously not use a straight return
statement as the method has a void
return type. Furthermore, I cannot set valueINeed = index
unless I make valueINeed final
. I am not sure I want to do that as what happens if the user changes his/her mind and I need to reassign the value?
Thanks!
Upvotes: 1
Views: 816
Reputation: 2897
TronicZomB's answer is correct, but you won't be notified when the global variable changes. If you need to do something with valueINeed
as soon as it's changed in the Spinner
, you have two options:
valueINeed
and put it all inside of the onItemSelected
functiononItemSelected
function.Example of #2:
subGoalSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
valueINeed = subGoalSpinner.getSelectedItemPosition();
updateView(valueINeed);
}
}
In this case, updateView
is a function that takes in valueINeed
as a parameter and does something with it (like updating a TextView
).
Upvotes: 0
Reputation: 8747
Just declare the variable int valueINeed;
as a global variable. Than you can use the following:
subGoalSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
valueINeed = subGoalSpinner.getSelectedItemPosition();
//I now want to somehow get the value of the index for use outside of this code block
}
Upvotes: 1