I’m trying to implement multiple spinners within one activity, which appears to be working ok. The problem I have is when I’m trying to output their options using onItemSelected, I can’t work out how to tell this method which spinner was just updated. I’ll copy the code in but here is the extract from the onItemSelected method. Which for example if I had two spinners would only show me results from intTypeItems spinner.
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(intTypeItems[position]);
}
Here is the full Class I’m working with.
public class Calculator extends Activity implements AdapterView.OnItemSelectedListener {
private TextView selection;
private static final Integer[] intNoItems={1,2,3};
//private static final String[] intNoItems={"one","two","three"};
private static final String[] intTypeItems={"Seconds","Minutes","Hours","Days"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
Spinner intNo=(Spinner)findViewById(R.id.intervalNo);
Spinner intType=(Spinner)findViewById(R.id.intervalType);
intNo.setOnItemSelectedListener(this);
intType.setOnItemSelectedListener(this);
selection=(TextView)findViewById(R.id.outPutValues);
ArrayAdapter<Integer> intNolist=new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item,intNoItems);
ArrayAdapter<String> intTypelist=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,intTypeItems);
intNolist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
intTypelist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
intNo.setAdapter(intNolist);
intType.setAdapter(intTypelist);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(casting + intTypeItems[position]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
One of the spinners is a int the other a string, so I’ll also need to cast the int to string when outputting to my selection text view. Which again I’m not sure how to do, as the cast would cause an exception when the string gets the callback?
You should have everything you need. Look at the call:
That first parameter,
parent, contains theViewthat the item belongs to. In your case, it will either beintNoorintType. If you kept those variables as fields, you could then test to see whichSpinneryou were in, like this: