How to set Error in Spinner in Android

ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{"item 1,item 2,item 3"});
YourSpinner.setAdapter(adapter)

You know setError works on EditText and TextView. If the spinner has a list of TextView or EditText item, then you simply have to get the TextView or Editext from it. And then set error on it. You can get TextView or EditText from Selected Spinner item view by this code demo below

TextView errorTextview = (TextView) YourSpinner.getSelectedView();
errorTextview.setError("Your Error Message here");
Show Error In Spinner 

Now the condition that checks spinner item is selected or not, if not then show an error.

if (YourSpinner.getSelectedItemPosition() > 0) {
// get selected item value
String itemvalue = String.valueOf(YourSpinner.getSelectedItem());
} else {
// set error message on spinner
TextView errorTextview = (TextView) YourSpinner.getSelectedView();
errorTextview.setError("Your Error Message here");
}

If the spinner not showing the error then you can pass the error message on the item with red color. see the code example below.

 TextView errorTextview = (TextView) spdisposition.getSelectedView();
 errorTextview.setError("");
 errorTextview.setTextColor(Color.RED);
// for show error message on spinner
 errorTextview.setText("Your Error Message here");
                    
show Error message Directly on spinner

One thought on “How to set Error in Spinner in Android

Leave a Reply

Your email address will not be published. Required fields are marked *