如何在Android中为Spinner设置错误消息?

时间:2015-01-30 12:12:45

标签: android android-widget spinner

我希望能够像这样调用代码,类似于在TextView上设置setError的方式:

spinner.setError("Error message");

但是,setError仅适用于EditText,而不适用于Spinner。

我想通知用户是否未选择微调器字段。如何在不使用Toast 的情况下执行此类通知

3 个答案:

答案 0 :(得分:63)

此帖子中有一些解决方案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);

答案 1 :(得分:28)

当您使用getSelectedView()时,Spinner类将返回textview。因此,您可以间接使用setError()

((TextView)spinner.getSelectedView()).setError("Error message");

结果应该像......

setError in spinner

希望它会有所帮助!

答案 2 :(得分:0)

针对正在寻找Kotlin答案的人

val errorText = spinnerclient.selectedView as TextView
                errorText.error = "client required"
                errorText.requestFocus()
                return@setOnClickListener

返回了焦点,但未显示文本。显示后,我将对其进行更新