-1

How to set validation on android spinner if user not select any thing from the dropdown at a time of form submission then validation message should be display. how it possible. search lot of thing in google but unable to do that. please anyone help me.

  • Possible duplicate of [Android Spinner validation](https://stackoverflow.com/questions/22267842/android-spinner-validation) – Mr. Roshan Jun 19 '18 at 12:26

3 Answers3

2
int value = 0;
String Text = String.valueOf(mySpinner.getSelectedItem());

then assign the value e.g.

if(Text == "BUS"){
 value = 20;
}
else if(Text == "TRAIN"){
 value = 10;
}
else{
 value = 0;
}

Then check whether value is 0 or not. if the value is 0 show the validation message

Zobair Alam
  • 527
  • 1
  • 5
  • 24
0

Define a variable globally to store selected item of spinner and set it empty or null according to value emit by the spinner

Store value in to that variable on item selected.

And at time of checking check the variable you have defined is not empty or null. If so then display toast of message.

Jay Thummar
  • 2,281
  • 1
  • 14
  • 22
0

How to do this :

  • Check if spinner is empty. Get the default selected view. Request Focus for the same view. Set some error message to be displayed.

You can also perform a click on the spinner so that the spinner list is displayed. (additional option).

Spinner mySpinner = (Spinner)findViewById(R.id.spinner_configurable_item);
                        int selectedItemOfMySpinner = mySpinner.getSelectedItemPosition();
                        String actualPositionOfMySpinner = (String) mySpinner.getItemAtPosition(selectedItemOfMySpinner);

                        if (actualPositionOfMySpinner.isEmpty()) {
                            setSpinnerError(mySpinner,getString("field can't be empty"));
                        }

private void setSpinnerError(Spinner spinner, String error){
    View selectedView = spinner.getSelectedView();
    if (selectedView != null && selectedView instanceof TextView) {
        spinner.requestFocus();
        TextView selectedTextView = (TextView) selectedView;
        selectedTextView.setError("error"); // any name of the error will do
        selectedTextView.setTextColor(Color.RED); //text color in which you want your error message to be displayed
        selectedTextView.setText(error); // actual error message 
        spinner.performClick(); // to open the spinner list if error is found.

    }
}