java - Android Spinner 在 OnCreate 中执行 ItemSelectedListener

标签 java android

在我的代码中,当您在微调器中选择一个项目时,应用程序会更改屏幕。但是,当它第一次加载时,它会执行 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/

相关文章:

java - 解释用Java创建金字塔

java - Spring Data Rest执行查询但返回500内部服务器错误

java - 如何增加 getRelativeDateTimeString 方法的耗时,以及如何增加正常日期的月份名称

java - Hibernate获取SQL query.list() : ArrayIndexOutOfBoundsException 0

java - 文件系统资源 : how to set relative path

android - 在 Android 应用中添加 Firebase Analytics 和 Google Analytics

java - 检测字符串中的字符是否为表情符号(使用 Android)

java - 在 Windows 资源管理器中看不到在 android 中创建的文件

android - 等待设备 : Could not start AVD, 虚拟化打开时出错

android - 使用MediaPlayer播放声音