0

这是实现 AdapterView.OnItemSelectedListener 的嵌套类。这提供了一个回调方法,当从 Spinner 中选择了一个项目时通知我的应用程序。但我不知道如何将 Selected String 值传递给主要活动?

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    String selected = parent.getItemAtPosition(pos).toString();
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
        // Do nothing.
  }

}

我像这样调用主要活动

     public void addListenerOnSpinnerItemSelection() {
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
     // I need the selected value here.........
  }
4

2 回答 2

0

如果您的侦听器是相关活动的嵌套子类,您应该能够直接从活动中简单地调用一个方法吗?

public void doSomething(String selected) {
    // do something here...
} 

public class YourItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        String selected = parent.getItemAtPosition(pos).toString();
        doSomething(selected); // <=== THIS
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}
于 2012-11-28T00:05:31.580 回答
0

在您的自定义 SpinnerAdapter 中,您可以将字符串设置为视图上的标签

 myFirstView.setTag("First");

在 onItemSelected 回调中,您可以从视图中获取标签。

 String selectedContent = (String)view.getTag();
于 2012-11-28T00:06:49.030 回答