这是实现AdapterView.OnItemSelectedListener的嵌套类。这提供了一个回调方法,当从Spinner中选择一个项目时,该方法通知我的应用程序。但我不知道如何将Selected String值传递给main活动?
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.........
}
答案 0 :(得分: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.
}
}
答案 1 :(得分:0)
在自定义SpinnerAdapter中,您可以将字符串设置为视图上的标记
myFirstView.setTag("First");
并且在onItemSelected回调中,您可以从视图中获取标记。
String selectedContent = (String)view.getTag();