2016-07-04 35 views
2

我有一個類稱爲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; 
    } 

} 
+0

'我收到回值是null' - 如果你想送點東西回來你的方法必須有一個返回類型(你的是無效的,即沒有),寫一個值_into_一個已經作爲參數傳遞的對象,或者將該值寫入可在方法調用後讀取的某個字段中。除非你知道你在做什麼,否則我不會推薦選項2和3給你(可能有你無法處理的副作用)。 – Thomas

+0

此外,如果您只是添加了監聽器,那麼'c.getStock();'能夠返回_any_值? 'onItemSelected()'不能在那個時候被調用。 – Thomas

+0

嗨,我不知道你在說什麼.. String stockCode = c.getStock();返回null。 getStock方法有一個字符串返回類型 –

回答

0

問題是,您在添加它後立即查詢偵聽器,即事件不可能發生。既然你不知道偶發生(如果有的話),你需要解耦。

實例(簡單的僞代碼,只是爲了讓你開始):

class Model { 
    String stock; 
} 

class Listener { 
    Model model; 

    Listener(Model m) { 
    model = m; 
    } 

    //In your case Component might be the spinner or its parent, depending on the rest of your code 
    void onItemSelected(Component c) { 
    m.stock = c.getText(); 
    } 
} 

當你創建和註冊監聽器:

class BuyCoins { 
    Model model; //initialize 

    ... 

    void initListeners() { 
    spinner.addListener(new Listener(model)); 
    } 
} 
+0

非常感謝..通過它快速工作 –

+0

仍在掙扎.. addListerner除了spinner1.setOnItemSelectedListener(c);所以如果我理解正確,你是添加額外的事件偵聽器到微調 –

+0

@the_big_blackbox沒有'addListener() '意味着'setOnItemSelectedListener()'在你的情況。正如我所說,它只是僞代碼(在大多數情況下,您可以添加多個偵聽器,因此「添加」 - 但如果只允許一個類型的偵聽器,「set」也可以)。 – Thomas

0

感謝大家,設法解決通過增加跟隨後續事件。

public void onBuyCoinButtonClicked(View arg0) { 

    spinner1 = (Spinner) findViewById(R.id.spinner1); 
    String product= spinner1.getSelectedItem().toString(); 
    Toast.makeText(this, 
      "product : " + product, 
      Toast.LENGTH_SHORT).show(); 

簡單的解決方法