Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to be able to call code like this, similar to how setError is set on a TextView:

spinner.setError("Error message"); 

However, setError only works for an EditText, not for a Spinner.

I want to notify the user if the spinner field is not selected. How can I perform such a notification without using a Toast?

like image 313
Gopinath S Avatar asked Jan 30 '15 12:01

Gopinath S


People also ask

How do you show error messages on android?

Solution: We can display error message in EditText by using setError() method. <?

How can I tell if spinner is clicked or not in android?

Let the Spinner's first value be something like "-please select-". when the user clicks on the next button perform validation and check whether the value of the selectedItem in the spinner is "-please select-" and if yes, then display a toast and ask the the user to select something from the spinner.


2 Answers

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); 
like image 52
Lionel T. Avatar answered Sep 28 '22 06:09

Lionel T.


Spinner class will return a textview when you use getSelectedView(). So you can use setError() indirectly.

((TextView)spinner.getSelectedView()).setError("Error message"); 

Results should be like ...

setError in spinner

Hope It will be helpful!

like image 28
Khan Avatar answered Sep 28 '22 06:09

Khan