How can I validate my Spinner Android Saripaar?
I have declared my Spinner in the following manner.
@Select(order = 8)
Spinner spin_country;
and this is my onValidationFailed() method.
@Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
// TODO Auto-generated method stub
String message = failedRule.getFailureMessage();
if (failedView instanceof Spinner) {
failedView.requestFocus();
// What should i do here??
} else {
}
}
If you want a simpler solution than provided by user3508814, just do the following (no need to track spinnerSelections):
Annotation used
@Select
Spinner spin_country;
onValidationFailed
@Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
String message = error.getCollatedErrorMessage(this);
// Display error messages
if (view instanceof EditText) {
((EditText) view).setError(message);
}
else if (view instanceof Spinner) {
((TextView) ((Spinner) view).getSelectedView()).setError(message);
}
}
}
Here is my solution.
Use a map to track spinners and their text views (if you have multiple).
private Map<View, TextView> spinnerSelections = new HashMap<View, TextView>();
Use OnItemSelectedListener to record changes to the spinner selection. This fires when the activity loads, so your default selection will be tracked.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerSelections.put(parent, (TextView) view);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Set errors on spinner's text view
@Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
String message = error.getCollatedErrorMessage(this);
if (view instanceof EditText) {
((EditText) view).setError(message);
}
else if (view instanceof Spinner) {
spinnerSelections.get(view).setError(message);
}
}
}
I set my spinners to not be focusable so I don't see any error messages but I do get the red exclamation point.
Hope this is helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With