Related spinners Android
I'm begginer in android. I'm working on a project. But i get very difficult to do two spinners related to each others. Actually one spinner for the country and another for the city. Instead of the country that is chosen the second spinner will show the cities.
I'v used "OnItemSelectedListener" but the " ArrayAdapter.createFromResource " can't be used inside OnItemSelectedListener. I've tried a lot of other ways but still none of them working. Can anybody help me Please???
(P.S. I have read and tried the other posts about this topic but it still doesn't work ) This is the code:
spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
int spinnerId = spinner.getSelectedItemPosition();
if (spinnerId==0){
adaptert = ArrayAdapter.createFromResource(
this, R.array.tirana, android.R.layout.simple_spinner_item);
adaptert.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
else if (开发者_如何学JAVAspinnerId==1) {
adaptert = ArrayAdapter.createFromResource(
this, R.array.durres, android.R.layout.simple_spinner_item);
adaptert.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
spinnert.setAdapter(adaptert);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
public class AdapterViewImplementation extends Activity implements OnItemSelectedListener{
Spinner sp1; // One Spinner
Spinner sp2; // Another Spinner
ArrayAdapter stateAdapter; // Adapter for state
ArrayAdapter cityAdapter; // Adapter for city
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sp1 = (Spinner)findViewById(R.id.Spinner01);
sp2 = (Spinner)findViewById(R.id.Spinner02);
stateAdapter = ArrayAdapter.createFromResource(AdapterViewImplementation.this,
R.array.state, android.R.layout.simple_spinner_item);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(stateAdapter);
sp1.setOnItemSelectedListener(AdapterViewImplementation.this);
cityAdapter = ArrayAdapter.createFromResource(AdapterViewImplementation.this,
R.array.city, android.R.layout.simple_spinner_item);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(cityAdapter);
sp2.setOnItemSelectedListener(AdapterViewImplementation.this);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arg0 == sp1){
sp2.setSelection(arg2);
}else{
sp1.setSelection(arg2);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
精彩评论