How to display validation error for a spinner widget similar to TextView.setError() I don't want to open a new dialog box for every spinner validation error, android.widget.Spinner class doesn’t have setError method
If your spinner is set-up with default item views the getSelectedView()
method on Spinner class will return a TextView
. And on that you can call setError(CharSequence)
Here is what I did:
View selectedView = spinner.getSelectedView();
if (selectedView != null && selectedView instanceof TextView) {
TextView selectedTextView = (TextView) selectedView;
if (!valid) {
String errorString = selectedTextView.getResources().getString(mErrorStringResource);
selectedTextView.setError(errorString);
}
else {
selectedTextView.setError(null);
}
}
Result looks like this on Android 4.4:
A somewhat cleaner way of doing Diederik's code:
static public void setSpinnerError(Spinner spinner, String error){
View selectedView = spinner.getSelectedView();
if (selectedView != null && selectedView instanceof TextView) {
TextView selectedTextView = (TextView) selectedView;
selectedTextView.setError(error);
}
}
Just set error
to null
if you want to dismiss it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With