我有一個類稱爲BuyCoins,在這一組內我有回調函數的java
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
TextView t=(TextView) findViewById(R.id.conversion);
CustomOnItemSelectedListener c = new CustomOnItemSelectedListener(t);
spinner1.setOnItemSelectedListener(c);
//String stockCode=c.getStock();
//Log.d(TAG,"message");
}
這產生其檢測項目(產品)的新對象上的旋塗器中選擇的方法addListenerOnSpinnerItemSelection()。 我想通過這回到BuyClass。我試圖用註釋掉的行來做到這一點,但是我收到的值是空的。
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
...
public String Stock;
...
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected=parent.getItemAtPosition(pos).toString();
switch(selected) {
case "20 Coins":
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + selected,
Toast.LENGTH_SHORT).show();
t.setText("$20");
this.setStock("20Coins");
break;
...
}
private void setStock(String s) {
Stock=s;
}
public String getStock() {
return Stock;
}
}
'我收到回值是null' - 如果你想送點東西回來你的方法必須有一個返回類型(你的是無效的,即沒有),寫一個值_into_一個已經作爲參數傳遞的對象,或者將該值寫入可在方法調用後讀取的某個字段中。除非你知道你在做什麼,否則我不會推薦選項2和3給你(可能有你無法處理的副作用)。 – Thomas
此外,如果您只是添加了監聽器,那麼'c.getStock();'能夠返回_any_值? 'onItemSelected()'不能在那個時候被調用。 – Thomas
嗨,我不知道你在說什麼.. String stockCode = c.getStock();返回null。 getStock方法有一個字符串返回類型 –