如何使“在所选项目上”不自动选择第一个条目

2022-09-03 09:11:49

我创建了一个微调器,当有人使用阵列适配器添加设备时,它会使用设备名称自动更新。我使用微调器创建了一个 OnItemSelected 方法,因此当选择微调器中的一个名称时,会出现一个新窗口。但是,当活动启动时,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);

答案 1

如果尝试避免对侦听器方法的初始调用,则另一个选项是使用来利用视图的消息队列。微调器首次检查侦听器时,尚未设置它。onItemSelected()post()

// 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) {
      }
    });
  }
});

答案 2

有谁知道一种不会自动选择列表中第一个项目的方法?

始终有一个选择,您无法更改它。Spinner

恕我直言,您不应该使用a来触发启动活动。Spinner

话虽如此,您可以使用 a 来跟踪这是否是第一个选择事件,如果是第一个选择事件,则忽略它。boolean


推荐