Reputation:
In my app I am using two spinners, so for the first spinner I select, lets say, village A and the second spinner village B. Then I would like to display the distance and time it would take between those selected values:
Here is my code:
Spinner spin1=(Spinner)findViewById(R.id.spinner1);
Spinner spin2=(Spinner)findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter1= ArrayAdapter.createFromResource(this, R.array.start_location, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> adapter2= ArrayAdapter.createFromResource(this, R.array.end_location, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin1.setAdapter(adapter1);
spin2.setAdapter(adapter2);
}
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (spin1.equals("Village A")) {
if (spin2.equals("Village B")) {
start.setText("60 Miles");
time.setText("3 Hours");
} else if (spin2.equals("Village A")) {
//Etc...
}
} else if (spin1.equals("Village C")) {
}
//Etc...
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
And:
<string-array name="start_location">
<item>Village A</item>
<item>Village B</item>
<item>Village C</item>
</string-array>
<string-array name="end_location">
<item>Village A</item>
<item>Village B</item>
<item>Village C</item>
</string-array>
Sorry if it is a stupid question, but is the first time working with spinners. Thank you in advance.
Upvotes: 0
Views: 42
Reputation: 1589
You should provide OnItemSelectedListener to each of the spinners and then you can override onItemSelected method and write your own logic
spin1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long id) {
//Your logic
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Similarly you can write for another spinner spin2
Upvotes: 2