java - 如何使 On Item Selected 不自动选择第一个条目

标签 java android eclipse spinner

我创建了一个微调器,当有人使用阵列适配器添加设备时,它会自动更新设备名称。 I created an OnItemSelected method with the spinner so when one of the names in the spinner is selected, a new window appears.但是,当 Activity 开始时,OnItemSelected 会自动选择列表中的第一项,因此在新窗口出现之前,用户没有机会实际进行选择。

代码如下:

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {
    // TODO Auto-generated method stub
    startActivity(new Intent("com.lukeorpin.theappliancekeeper.APPLIANCESELECTED"));
    }

public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

有谁知道列表中的第一项不会被自动选中的方法吗?

这是微调器其余部分的代码:

ArrayAdapter<String> appliancenameadapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, ApplianceNames); //Sets up an array adapter containing the values of the ApplianceNames string array
    applianceName = (Spinner) findViewById(R.id.spinner_name); //Gives the spinner in the xml layout a variable name
    applianceName.setAdapter(appliancenameadapter); //Adds the contents of the array adapter into the spinner

    applianceName.setOnItemSelectedListener(this);

最佳答案

如果您试图避免初始调用监听器的 onItemSelected() 方法,另一种选择是使用 post() 来利用 View 的消息队列.微调器第一次检查您的监听器时,它尚未设置。

// Set initial selection
spinner.setSelection(position);

// Post to avoid initial invocation
spinner.post(new Runnable() {
  @Override public void run() {
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // Only called when the user changes the selection
      }

      @Override
      public void onNothingSelected(AdapterView<?> parent) {
      }
    });
  }
});

关于java - 如何使 On Item Selected 不自动选择第一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132971/

相关文章:

android studio gradle 服务器配置

Eclipse Spring Boot 构建路径包含重复条目

C++ 运算符重载的 Java 等价物

java - 如何将 Oracle 的 APPEND 提示与 JOOQ 渲染的 INSERT 语句一起使用?

android - 撤消在android中自定义 ImageView 上的绘制

java - 如何序列化自定义对象列表并在 Android 中的 RestoreInstanceState 上恢复它?

java - 机器人在最小化应用程序中运行

Java - 在未安装 SWT 的情况下运行 SWT 相关程序

java - 在 Mac 上为 Java 1.7 编译 rJava

java - Android Studio - 关闭芯片图标不执行任何操作(Java)