I would like to have a certain action when a specific item is selected (e.g. item 2), but have a generic action occur for any others (e.g. items 1, 3, 4).
This is my code:
private String[] array_spinner = new String[4];
private thetiki mContext;
/** Called when the activity is first created. */
开发者_运维知识库 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.main2);
array_spinner[0] = "Mathimatika Genikis Paideias";
array_spinner[1] = "Fusiki Genikis Paideias";
array_spinner[2] = "Istoria Genikis Paideias";
array_spinner[3] = "Viologia Genikis Paideias";
Spinner s = (Spinner)findViewById(R.id.spinner);
ArrayAdapter adapter =
new ArrayAdapter(this, android.R.layout.simple_spinner_item,
array_spinner);
s.setAdapter(adapter);
// more code
apostoli.setOnClickListener(new OnClickListener() {
private AlertDialog show;
public void onClick(View arg0) {
if (...) {
if (array_spinner[2] != null) {
//do something
} else if (array_spinner[0] != null || array_spinner[1] != null || array_spinner[3] != null) {
//do something else
}
}
array_spinner[index] will never be null in this case. You've already initialized them, how could they be? You need to set up a listener to handle selections in the Spinner, something like this:
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(pos == 2) {
//do specific action
} else {
//do generic action
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//do nothing
}
});
See more information in the Spinner tutorial.
精彩评论