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

Ske*_*zii 8 java eclipse android 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
Run Code Online (Sandbox Code Playgroud)

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

以下是其余微调器的代码:

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);
Run Code Online (Sandbox Code Playgroud)

Jam*_*ald 20

如果您试图避免对侦听器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) {
      }
    });
  }
});
Run Code Online (Sandbox Code Playgroud)


Com*_*are 8

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

总是一个选择Spinner,你不能改变的.

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

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

  • @Caumons:我永远不会想把`Spinners`放在`ListView`中. (3认同)

kar*_*ran 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...
        }

    }
Run Code Online (Sandbox Code Playgroud)