简体   繁体   English

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

[英]Passing a variable from one class to another in java

I have an android app and I need to pass a variable (instrument) to its main activity. 我有一个Android应用程序,我需要将一个变量(仪器)传递给它的主要活动。 It may seem like a simple question, but it confuses me. 这似乎是一个简单的问题,但它让我感到困惑。 I looked around and I already noticed that it seems like a good idea to write a getInstrument method. 我环顾四周,我已经注意到编写一个getInstrument方法似乎是一个好主意。 This is what I did so far: 这是我到目前为止所做的:

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());

    }
}

seperate class (in seperate file): 单独的类(在单独的文件中):

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;
  }

}

But I don't think I can call the getInstrument() method from the main activity, since the object only exists within the listener. 但我不认为我可以从主活动调用getInstrument()方法,因为该对象仅存在于侦听器中。 There must be a really simple way around it. 必须有一个非常简单的方法。 I read some posts, but the problem seems to be that the object of the class does not really exist. 我读了一些帖子,但问题似乎是该类的对象并不存在。 Thanks for any insights. 感谢您的任何见解。

You can try this : 你可以试试这个:

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);  
   }
}

If you have a reference to your listener, you should be able to call its methods, eg. 如果你有一个对你的听众的引用,你应该能够调用它的方法,例如。

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

Create a global instance of the 创建一个全局实例

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

This will be on the MainActivity class 这将在MainActivity类上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM