我试图让几个微调器根据他们之前的微调器选择动态更改。我可以更新列表,但是当我使用 adapter.clear() 时它会崩溃。这是我的代码:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class CarKitsAct extends Activity{
ArrayAdapter<String> adMod, adEd;
String[] models, edition;
Boolean initSpMan = true;
Boolean initSpMod = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.carkitslayout);
// Construct TextViews
TextView textMan = (TextView) findViewById(R.id.textMan);
textMan.setText(R.string.selectmanufacturer);
TextView textMod = (TextView) findViewById(R.id.textMod);
textMod.setText(R.string.selectmodel);
TextView textEd = (TextView) findViewById(R.id.textEd);
textEd.setText(R.string.selectedition);
// Construct Spinners
Spinner spMan = (Spinner) findViewById(R.id.spMan);
Spinner spMod = (Spinner) findViewById(R.id.spMod);
Spinner spEd = (Spinner) findViewById(R.id.spEd);
// Construct Manufacturer Spinner Adapter
ArrayAdapter<CharSequence> adMan;
adMan = ArrayAdapter.createFromResource(this, R.array.cars, android.R.layout.simple_spinner_item);
adMan.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMan.setAdapter(adMan);
// Set initial values for model and edition spinners
models = getResources().getStringArray(R.array.AC);
edition = getResources().getStringArray(R.array.ACAcceca);
//Construct adapters for models and editions
adMod = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, models);
adMod.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adMod.setNotifyOnChange(true);
spMod.setAdapter(adMod);
adEd = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, edition);
adEd.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adEd.setNotifyOnChange(true);
spEd.setAdapter(adEd);
// Set up listeners for item selection
spMan.setOnItemSelectedListener(new ManItemSelectedListener());
}
public class ManItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (initSpMan == true) {
initSpMan = false;
} else {
models = getResources().getStringArray(2130968577 + pos);
adMod.clear();
adMod.addAll(models);
adMod.notifyDataSetChanged();
}
}
public void onNothingSelected(AdapterView<?> parent) {}
}
}
如您所见,我尝试使用布尔标志来确定微调器是否刚刚创建,但是当我更改选择时,它会死掉。