Creating a Seterror() for The Spinner

How can an error message be set for the Spinner in Android?

There are a few solutions in this thread Creating a setError() for the Spinner:

The EdmundYeung99's one works for me, either you are using your own adapter or not.
Just put the following code in your validate function:

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

But, make sure you have at least one value in the Spinner adapter when you are doing your verification. If not, like an empty adapter waiting to be populate, make your adapter get an empty String:

ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{""});
mySpinner.setAdapter(adapter);

Spinner with error in Android

First of all: The different pages you see when you create a new Google account on your device are simply a WebView. So they aren't using native components / widgets.

By default the Spinner Widget doesn't have a setError(...) method like the EditText (which is derived from the TextView by the way). So to show an error inside a Spinner you have to get the View of the currently selected item first and cast it as a TextView (see this answer).

Note: ClassCastException will occur if you're using a layout of which the root element isn't a TextView.

Here's the catch of this approach: It won't look like the error message in your example or the error message of the TextInputLayout.

So in order to achieve the desired effect you have to use a third party library or implement it on your own.

Further note: If you look at the source code of the MaterialSpinner library you can see that it extends the AppCompatSpinner class and adds additional methods like the setError method you've mentioned. If you look at the onDraw(...) method you can see how the error is shown.

Android: for loop through EditText, CheckBoxed and Spinners to setErrors

You can check if the current view is an instance of a textview. If it is, then go ahead and cast it to a TextView, and perform whatever operations you were performing over it. Else, handle checkboxes/spinner/whatever in any way you'd like.

 for (Map.Entry<String, List<String>> error : errors.entrySet()) {
int id = getActivity().getResources().getIdentifier("edit_" + error.getKey(), "id", getActivity().getPackageName());

View edit = getActivity().findViewById(id);
if (!error.getValue().isEmpty() && edit instanceof TextView) {
TextView editTextView = (TextView)edit;
editTextView.setError(error.getValue().get(0));
}
}


Related Topics



Leave a reply



Submit