Updated 18 December 2016
Hello Everyone,
This blog is quite easy to understand and implement.
We all use spinner to display a list of selectable options and make our app interface more interactive .
In order to make app UI more interactive, we all try to set and point the error exactly at the view which is left empty. Let’s see how to do this on a spinner.
Concept :
A Spinner in android is actually a collection of textviews that are listed according to the number of entries in the list.
All you need to do is, to check if the spinner is empty and then select the default text view and set error message on that text view.
How to do this :
CODE :
calling error method if spinner is empty :
1 2 3 4 5 6 7 |
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")); } |
spinner error method :
1 2 3 4 5 6 7 8 9 10 11 12 |
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. } } |
And it is done .
Check it out and I believe this makes UI better.
Keep coding and Keep Sahring.
References: http://stackoverflow.com/a/28582158
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Why is it?
Any mistyped?
Thanks