1

这就是我定义微调器的方式

s_province = (Spinner) findViewById(R.id.s_province);
        ArrayAdapter<String> provinceAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, Data.provinces);
        provinceAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s_province.setAdapter(provinceAdapter);
        s_province.setOnItemSelectedListener(this);

我的类是从实现的OnItemSelectedListener,我覆盖了这个方法

@Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        switch (arg1.getId()) {
        case R.id.s_province:
            Log.d("here", "there");
            break;

        default:
            break;
        }
    }

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

    }

但是onItemSelect没有触发,为什么?

4

1 回答 1

2

Two things:

  1. If you actually want to check if your method is working put a Log statement outside the switch or in the default case so that you can be sure the method is being called.

  2. You should be using arg2 since that represents position. Make your switch work with positions instead of whatever View is passed. Also rename your variables from the default names Eclipse assigns. arg0,1,2, etc are not helpful for you nor for anyone else looking at your code.

Eg

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
  Toast.makeText(view.getContext(),"onItemSelected called", Toast.LENGTH_LONG).show();
  int spinnerId = parent.getId();
  if (spinnerId == R.id.s_province)
  {
    switch (position)
    {
      case 0: 
        //do something if first position was clicked
      break:
      case 1:
        //do something else
        break;
      default: 
        //if for any reason no position matches.
        break;
    }
  }
  else if (spinnerId == R.other_id_in_xml)
  {
    switch (position)
    {
      case 0: 
        //do something if first position was clicked
      break:
      case 1:
        //do something else
        break;
      default: 
        //if for any reason no position matches.
        break;
    }
  }
  //etc
}
于 2013-02-01T22:24:39.807 回答