在java中将变量从一个类传递到另一个类

时间:2012-11-28 16:27:59

标签: java android class variables listener

我有一个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;
  }

}

但是我不认为我可以从main活动调用getInstrument()方法,因为该对象只存在于监听器中。必须有一个非常简单的方法。我读了一些帖子,但问题似乎是该类的对象并不存在。感谢您的任何见解。

3 个答案:

答案 0 :(得分: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);  
   }
}

答案 1 :(得分:1)

如果你有一个对你的听众的引用,你应该能够调用它的方法,例如

CustomOnItemSelectedListener listener = new CustomOnItemSelectedListener();
instrumentSp.setOnItemSelectedListener(listener);
....
int instrumentValue = listener.getInstrument();

答案 2 :(得分:0)

创建

的全局实例
CustomOnItemSelectedListener listener;
int instrument;
public void onCreate(Bundle b){
    listener = new CustomOnItemSelectedListener();
    instrument = listener.getInstrument();
}

这将在MainActivity类

相关问题