Android spinner position and if statements

2019-07-28 03:39发布

问题:

Having an odd issue here and don't know why it doesn't work, I'm not that used to java yet. to determine the selected item what needs to be done? the spinner has 8 items and 'position' never = 1, or any other number. onItemSelected() is definitely getting fired so is the if statement wrong?

public void onItemSelected(AdapterView parent, View v,int position, long id) {

    if (position == 1) //do something
}

EDIT: thanks Lion it turns out position doesnt seem to do anything. however, this works.

String s = parent.getSelectedItem().toString();
if (s == "1")//do something

回答1:

You have to implement the proper listener for the spinner.

yourSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 

      @Override
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
              if (position == 1){
                 //Do something}
              }
      }

      @Override
      public void onNothingSelected(AdapterView parent) {
                  // Do nothing.
      }           
 });

If you're "not that used to Java" I recommend you read some basics.