在我的代码中,当您在微调器中选择一个项目时,应用程序会更改屏幕。但是,当它第一次加载时,它会执行 ItemSelectedListener。仅当我在微调器中选择一个项目时,而不是在加载表单时,我才需要它来执行代码。
代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_location_layout);
Spinner spnEUID = (Spinner)findViewById(R.id.spnEUID);
final DatabaseHandler handler = new DatabaseHandler(this);
ArrayList<String> EUIDs = handler.GetAllAOI();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, EUIDs);
spnEUID.setAdapter(adapter);
final EditText txtEUID = (EditText)findViewById(R.id.txtScanEUID);
txtEUID.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
PublicVariables.AOI = handler.getAOI(Integer.parseInt(txtEUID.getText().toString()));
Intent intent = new Intent(SelectLocationScreen.this, RaploScanScreen.class);
startActivity(intent);
}
return false;
}
});
spnEUID.setOnItemSelectedListener(new OnItemSelectedListener () {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
PublicVariables.AOI = parent.getItemAtPosition(pos).toString();
Intent intent = new Intent(SelectLocationScreen.this, RaploScanScreen.class);
startActivity(intent);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
最佳答案
我通过在 OnItemSelectedListener 中添加一个类似 previousSelection
的变量解决了这个问题:
- 如果为
null
,则为误报。 - 如果不是,则用户做出了此选择。
这是我对类似问题的回答,我写这个是为了避免您的问题以及当用户再次选择同一项目时。 Odd Android Spinner behavior
关于java - Android Spinner 在 OnCreate 中执行 ItemSelectedListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15418883/