Spinner with error in Android

十年热恋 提交于 2020-01-24 12:38:28

问题


I'm using a Spinner with the new style

Base.Widget.AppCompat.Spinner.Underlined

I can see the underline and the line is shown with the accent color while I'm selecting the option.

The problem is that I could not find a way to show the error with the red underline like Google does for all its app for the date of birth for example.

To see the error try to add a new account in any of the Google apps. It will ask you for the date of birth. Enter an invalid date and then press next.

Is there a way to do it without using the third party MaterialSpinner library?


回答1:


First of all: The different pages you see when you create a new Google account on your device are simply a WebView. So they aren't using native components / widgets.

By default the Spinner Widget doesn't have a setError(...) method like the EditText (which is derived from the TextView by the way). So to show an error inside a Spinner you have to get the View of the currently selected item first and cast it as a TextView (see this answer).
Note: ClassCastException will occur if you're using a layout of which the root element isn't a TextView.

Here's the catch of this approach: It won't look like the error message in your example or the error message of the TextInputLayout.
So in order to achieve the desired effect you have to use a third party library or implement it on your own.

Further note: If you look at the source code of the MaterialSpinner library you can see that it extends the AppCompatSpinner class and adds additional methods like the setError method you've mentioned. If you look at the onDraw(...) method you can see how the error is shown.



来源:https://stackoverflow.com/questions/39792721/spinner-with-error-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!