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!
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
}
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
function onItemSelected
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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.