我希望能够像这样调用代码,类似于在TextView上设置setError
:
spinner.setError("Error message");
但是,setError
仅适用于EditText,而不适用于Spinner。
我想通知用户是否未选择微调器字段。如何在不使用Toast的情况下执行此类通知?
这个主题Creating a setError() for the Spinner中有一些解决方案:
EdmundYeung99适用于我,无论您是否使用自己的适配器。只需将以下代码放入验证函数中:
TextView errorText = (TextView)mySpinner.getSelectedView();
errorText.setError("");
errorText.setTextColor(Color.RED);//just to highlight that this is an error
errorText.setText("my actual error text");//changes the selected item text to this
但是,在进行验证时,请确保Spinner适配器中至少有一个值。如果没有,就像一个空的适配器等待填充,让你的适配器得到一个空字符串:
ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{""});
mySpinner.setAdapter(adapter);
当您使用getSelectedView()
时,Spinner类将返回textview。所以你可以间接使用setError()
。
((TextView)spinner.getSelectedView()).setError("Error message");
结果应该像......
希望它会有所帮助!
Here is a solution除了使用微调器中的错误图标外,还使用隐藏的TextView来显示弹出消息。处于错误状态时,Spinner看起来像这样:
当不处于错误状态时,它看起来像这样。
这里记录了完整的解决方案:https://stackoverflow.com/a/29956372/3063884