Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display validation error for a spinner widget similar to TextView.setError()

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

like image 748
user2708445 Avatar asked Sep 30 '13 18:09

user2708445


2 Answers

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:

Spinner with error

like image 157
Diederik Avatar answered Nov 14 '22 01:11

Diederik


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.

like image 35
Muz Avatar answered Nov 14 '22 01:11

Muz