Very new to Android development.
I have been referencing this StackOverflow thread: Android: two Spinner onItemSelected(), but thus far have been running into issues with trying to build a simple program with two spinners and a submit button. The simple program I am trying to develop captures whatever is selected in both Spinners and on submit, does 'something'.
If I use the below onItemSelectedListener, how do I implement an onClick Listener that captures whatever is currently selected in both spinners? Does the same 'View' get passed to the 'onClick' listener or no?
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.spinner1)
{
//do this
}
else if(spinner.getId() == R.id.spinner2)
{
//do this
}
}
Thanks so much for your help!
EDIT
After implmenting Nolly J's suggested code, I am almost there. It seems like the spinnerFromValue and spinnerToValue strings are still not being set. I have:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
distValue = (EditText) findViewById(R.id.distValue);
distResult = (EditText) findViewById(R.id.distResult);
this.arraySpinner = new String[]{"Miles", "Kilometers", "Meters", "Feet", "Inches", "Centimeters"};
Spinner spinnerFrom = (Spinner) findViewById(R.id.spinnerFrom);
Spinner spinnerTo = (Spinner) findViewById(R.id.spinnerTo);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arraySpinner);
spinnerFrom.setAdapter(adapter);
spinnerTo.setAdapter(adapter);
buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// use the two variables to do what you want.
// Example
distResult.setText(spinnerFromValue + spinnerToValue);
}
});
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Spinner spinner = (Spinner) parent;
spinnerFromValue = parent.getSelectedItem().toString();
spinnerToValue = parent.getSelectedItem().toString();
if(spinner.getId() == R.id.spinnerFrom){
//do this
spinnerFromValue = parent.getSelectedItem().toString();
}
else if(spinner.getId() == R.id.spinnerTo){
//do this
spinnerToValue = parent.getSelectedItem().toString();
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
Any ideas?