我希望微调器在我运行活动时自行打开,因此我使用performClick()
方法,但它显示此错误:
引起:android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
我该怎么办? 这是我的代码
public class FacilityComplaint extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner spinner1;
private static final String[] suggestions = {"Select from suggestions", "Switch not working",
"Switch faulty", "Switch light not working", "Switch handle faulty"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facility_complaint);
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(FacilityComplaint.this,
android.R.layout.simple_spinner_item, suggestions);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(this);
spinner1.performClick();
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
switch (position) {
case 0:
//do something
break;
case 1:
//do something
break;
case 2:
//do something
break;
case 3:
//do something
break;
case 4:
//do something
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
答案 0 :(得分:1)
对于微调器,您不需要实现&#34; AdapterView.OnItemSelectedListener&#34;像这样创造。
spinner1 = (Spinner) findViewById(R.id. spinner1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
suggestions, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.performClick();
//获取选择索引或建议
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String selectedSugg = suggestions[pos];
Log.d("Suggestions ", selectedSugg);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});