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

时间:2012-04-12 22:48:44

标签: java android eclipse spinner

我创建了一个微调器,当用户使用阵列适配器添加设备时,该微调器会自动使用设备名称进行更新。我使用微调器创建了一个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);

3 个答案:

答案 0 :(得分:19)

如果您尝试避免初始调用侦听器的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) {
      }
    });
  }
});

答案 1 :(得分:7)

  

有没有人知道列表中第一项不会自动选择的方式?

始终选择Spinner,您无法更改。

恕我直言,你不应该使用Spinner来触发开始活动。

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

答案 2 :(得分:6)

它对我有用,

private boolean isSpinnerInitial = true;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view,
            int position, long id) {

        if(isSpinnerInitial)
        {
            isSpinnerInitial = false;
        }
        else  {
            // do your work...
        }

    }