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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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:
回答2:
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.
回答3:
So, you can use 'setError' in your getView in the adapter of spinner. Of course, if your item's xml of your spinner has a TextView:
if(requeriedField && item.getValue() == 0){
img_tittle_spinner.setError(activity.getResources().getString(R.string.FieldRequired));
}