我是Android的新手。尝试获取微调框的选定项目时,我得到的值为空。
我尝试设计两个微调器,然后单击按钮,将微调器的选定项之一写入文本字段。但是我越来越空了。您能解释一下原因吗?
public class EERActivity extends AppCompatActivity implements
OnItemSelectedListener {
private Spinner spinner1;
private Spinner spinner2;
private String[] array1= {"xx","yy"};
private String[] array2= {"x2", "y2"};
private ArrayAdapter<String> dataAdapterForArray1;
private ArrayAdapter<String> dataAdapterForArray2;
String selected1;
String selected2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eer);
spinner1 = (Spinner)findViewById(R.id.spinner2);
spinner2 = (Spinner)findViewById(R.id.spinner3);
dataAdapterForArray1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, array1);
//and 2 is here..//
spinner1.setAdapter(dataAdapterForArray1);
spinner2.setAdapter(...filled...);
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if(parent.getId() == R.id.spinner2) {
selected1 = spinner1.getSelectedItem().toString();
}
else if(parent.getId() == R.id.spinner3){
selected2 = spinner2.getSelectedItem().toString();
}
selectedSpinner1 = spinner1.getSelectedItem().toString();
selectedSpinner2 = spinner2.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
public void run (View view){
textView.setText("Result: " + selected1); }
我希望从spinner1中选择输出,但结果为空。
答案 0 :(得分:0)
最有可能在微调器组件中实际更改值之前触发了事件。为了解决这个问题,您可以添加一个空检查。尝试在“ onItemSelected”方法的第一行中添加以下内容:
if ((parent.getId() == R.id.spinner2 && spinner1.getSelectedItem() == null) || (parent.getId() == R.id.spinner3 && spinner2.getSelectedItem() == null)) {
return ;
}
此外,我不确定您是否发布了整个代码,但这看起来是错误的:
spinner1 = (Spinner)findViewById(R.id.spinner2);
spinner2 = (Spinner)findViewById(R.id.spinner3);