0

我有一个 android 应用程序,我需要将一个变量(仪器)传递给它的主要活动。这似乎是一个简单的问题,但它让我感到困惑。我环顾四周,我已经注意到编写 getInstrument 方法似乎是个好主意。这是我到目前为止所做的:

public class MainActivity extends Activity{
//I need to read the instrument variable here
    public void addListenerOnSpinnerItemSelection(){

        instrumentSp = (Spinner) findViewById(R.id.instrument);
        instrumentSp.setOnItemSelectedListener(new CustomOnItemSelectedListener());

    }
}

单独的类(在单独的文件中):

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

private int instrument;

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(), 
        "Please wait a minute for the instrument to be changed. ", Toast.LENGTH_SHORT).show();
        //"Item : " + parent.getItemAtPosition(pos).toString() + " selected" + pos,
        //Toast.LENGTH_SHORT).show();
     instrument = pos;
  }


  public int getInstrument(){
      return instrument;
  }

}

但我认为我不能从主要活动中调用 getInstrument() 方法,因为该对象仅存在于侦听器中。必须有一个非常简单的方法来解决它。我读了一些帖子,但问题似乎是该类的对象并不真正存在。感谢您的任何见解。

4

3 回答 3

1

你可以试试这个:

public class MainActivity extends Activity{
   //I need to read the instrument variable here
   CustomOnItemSelectedListener MyListener = new CustomOnItemSelectedListener();

   public void addListenerOnSpinnerItemSelection(){

     instrumentSp = (Spinner) findViewById(R.id.instrument);
     instrumentSp.setOnItemSelectedListener(MyListener);  
   }
}
于 2012-11-28T16:29:54.683 回答
1

如果您有对侦听器的引用,您应该能够调用它的方法,例如。

CustomOnItemSelectedListener listener = new CustomOnItemSelectedListener();
instrumentSp.setOnItemSelectedListener(listener);
....
int instrumentValue = listener.getInstrument();
于 2012-11-28T16:32:08.407 回答
0

创建一个全局实例

CustomOnItemSelectedListener listener;
int instrument;
public void onCreate(Bundle b){
    listener = new CustomOnItemSelectedListener();
    instrument = listener.getInstrument();
}

这将在 MainActivity 类

于 2012-11-28T16:33:05.497 回答