我希望能够像在TextView上设置setError
一样,调用如下代码:
spinner.setError("Error message");
然而,setError
仅适用于EditText,不适用于Spinner。
如果Spinner字段未被选中,我想通知用户。我该如何进行此类通知而不使用Toast?
我希望能够像在TextView上设置setError
一样,调用如下代码:
spinner.setError("Error message");
然而,setError
仅适用于EditText,不适用于Spinner。
如果Spinner字段未被选中,我想通知用户。我该如何进行此类通知而不使用Toast?
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适配器中至少有一个值。如果没有,就像等待填充的空适配器一样,请让您的适配器获取一个空字符串:
但是,请确保在进行验证时,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");
结果应该像这样...
希望它会有所帮助!
这里有一个解决方案,它使用隐藏的TextView来显示弹出消息,除了下拉列表中的错误图标。当处于错误状态时,Spinner看起来像这样:
针对正在寻找 Kotlin 答案的人
val errorText = spinnerclient.selectedView as TextView
errorText.error = "client required"
errorText.requestFocus()
return@setOnClickListener
焦点已返回,但文本没有显示。一旦它被显示出来,我会进行更新。