2016-07-04 37 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(); 

简单的解决方法