在 Android 中出现错误的微调器

Spinner with error in Android

我正在使用新样式的 Spinner

Base.Widget.AppCompat.Spinner.Underlined

当我选择选项时,我可以看到下划线,并且线条以强调色显示。

问题是我无法找到一种方法来显示带有红色下划线的错误,例如 Google 对其所有应用程序的出生日期所做的那样。

要查看错误,请尝试在任何 Google 应用中添加一个新帐户。它会询问你的出生日期。输入无效日期,然后按下一步。

有没有不使用第三方MaterialSpinner库的方法?

首先:您在设备上创建新 Google 帐户时看到的不同页面只是一个 WebView。所以他们没有使用本机组件/小部件。

默认情况下,Spinner 小部件没有 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)。
注意:如果您使用的布局的根元素不是 TextView,则会发生 ClassCastException。

此方法的关键在于:它看起来不像您示例中的错误消息或 TextInputLayout.
中的错误消息 所以为了达到你想要的效果你必须使用第三方库或者自己实现。

进一步说明:如果您查看 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(...) 方法,您可以看到错误是如何显示的。