如何为 Android 中的 Spinner 设置错误消息?
How can an error message be set for the Spinner in Android?
我希望能够像这样调用代码,类似于在 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 class 将 return 一个文本视图。所以你可以间接使用setError()
。
((TextView)spinner.getSelectedView()).setError("Error message");
结果应该像...
希望对您有所帮助!
Here is a solution 除了微调器中的错误图标外,它还使用隐藏的 TextView 来显示弹出消息。当处于错误状态时,微调器看起来像这样:
不处于错误状态时,它看起来像这样。
完整的解决方案记录在此处:
对于正在寻找 Kotlin 答案的人
val errorText = spinnerclient.selectedView as TextView
errorText.error = "client required"
errorText.requestFocus()
return@setOnClickListener
焦点已返回,但文本未显示。显示后我会更新
我希望能够像这样调用代码,类似于在 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 class 将 return 一个文本视图。所以你可以间接使用setError()
。
((TextView)spinner.getSelectedView()).setError("Error message");
结果应该像...
希望对您有所帮助!
Here is a solution 除了微调器中的错误图标外,它还使用隐藏的 TextView 来显示弹出消息。当处于错误状态时,微调器看起来像这样:
不处于错误状态时,它看起来像这样。
完整的解决方案记录在此处:
对于正在寻找 Kotlin 答案的人
val errorText = spinnerclient.selectedView as TextView
errorText.error = "client required"
errorText.requestFocus()
return@setOnClickListener
焦点已返回,但文本未显示。显示后我会更新