簡體   English   中英

在java中將變量從一個類傳遞到另一個類

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

我有一個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()方法,因為該對象僅存在於偵聽器中。 必須有一個非常簡單的方法。 我讀了一些帖子,但問題似乎是該類的對象並不存在。 感謝您的任何見解。

你可以試試這個:

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

如果你有一個對你的聽眾的引用,你應該能夠調用它的方法,例如。

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

創建一個全局實例

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

這將在MainActivity類上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM