Using Spinner selection as a value in Android
문제
I am trying to get a Spinner to work in Android. It displays fine and I can select any one of the options in the list. But how do I transfer that to a string? I would have thought in the code below that 'selected' would hold the selected string, but I get an 'Illegal modifier for the local class YourItemSelectedListener; only abstract or final is permitted' error on the 'YourItemSelectedListener'. What am I doing wrong? Many thanks for any help.
Spinner spinnerFPS = (Spinner) findViewById(R.id.sp_FPS);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.framesps, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFPS.setAdapter(adapter);
spinnerFPS.setOnItemSelectedListener(new YourItemSelectedListener());
public class YourItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
해결책
Since you are using an array resource for spinner create a resource handle
with local array declaration with getResources().getStringArray(R.array.framesps);
and then use that handle to access the selected item using position variable:
items[pos]
Heres a code edit:
Spinner spinnerFPS = (Spinner) findViewById(R.id.sp_FPS);
String[] items=getResources().getStringArray(R.array.framesps);//handle to your arrays
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFPS.setAdapter(adapter);
spinnerFPS.setOnItemSelectedListener(new YourItemSelectedListener());
public class YourItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected =items[pos]; // use handler to access select item
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
다른 팁
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, items, android.R.layout.simple_spinner_item);
You will have to add the CurrentActivityName.this
. This will fix the issue. You just can't pass the argument context as this
. You will have to put ActivityName.this
.