错误(或提示)文本的Android TextInputLayout图标

jam*_*mes 6 android kotlin android-drawable

我正在使用TextInputLayoutHelper小部件,以便遵循浮动标签输入的材料准则。当前看起来像这样:

带有错误消息的浮动输入标签

我的密码

在活动onCreate功能中,我具有:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val passwordInputLayout = this.findViewById<TextInputLayoutHelper>(R.id.input_layout_password)
    passwordInputLayout.error = "8+ characters and at least one uppercase letter, a number, and a special character (\$, #, !)"
    passwordInputLayout.isErrorEnabled = true
}
Run Code Online (Sandbox Code Playgroud)

和我的小部件xml看起来像...

<TextInputLayout
    android:id="@+id/input_layout_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/EditTextTheme"
    app:errorEnabled="true"
    app:errorTextAppearance="@style/ErrorAppearance"
    app:passwordToggleDrawable="@drawable/asl_password_visibility"
    app:passwordToggleEnabled="true"
    app:passwordToggleTint="?colorControlNormal">

    <EditText
        android:id="@+id/password_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/set_a_password"
        android:inputType="textPassword"
        android:singleLine="true" />

</TextInputLayout>
Run Code Online (Sandbox Code Playgroud)

我想做的事

我想在错误文本的右侧的错误/提示文本(感叹号三角形)中放置一个图标。

模拟带有错误图标的输入

我的尝试

尝试1

我发现使用了一个实现setError(text, drawable)但我正在使用的Kotlin实现setError不可用。

所以我尝试了:

val warningIcon = ResourcesCompat.getDrawable(resources, R.drawable.ic_warning_black_24dp, null)
warningIcon?.setBounds(0, 0, warningIcon.intrinsicWidth, warningIcon.intrinsicHeight)

passwordInputLayout.error = "8+ characters and at least one uppercase letter, a number, and a special character (\$, #, !) $warningIcon"
Run Code Online (Sandbox Code Playgroud)

但这不会渲染可绘制对象,而只是渲染资源路径的字符串。

尝试2

我发现了另一个可以覆盖的TextInputLayoutHelper控件,以便在文本旁边设置可绘制对象。如您所见,setError仅包含override fun setError(error: CharSequence?)不带参数的接口drawable

override fun setError(error: CharSequence?) {
    super.setError(error)

    val warningIcon = ResourcesCompat.getDrawable(resources, R.drawable.ic_warning_black_24dp, null)
    warningIcon?.setBounds(0, 0, warningIcon.intrinsicWidth, warningIcon.intrinsicHeight)
    // mHelperView is a TextView used in my custom `TextInputLayout` override widget
    mHelperView!!.setCompoundDrawables(null, null, warningIcon, null)
}
Run Code Online (Sandbox Code Playgroud)

是否有替代项或内置的“ Android方式”在错误/提示文本旁边添加此图标?

Hes*_*sam 0

这可能会帮助其他遇到类似麻烦的人。我查看了源代码。事情是setError(text, drawable)在 EditText 类中定义的,而不是TextInputLayout您的布局所基于的。

我有像你一样的类似代码和问题,并且由于TextInputLayout没有任何方法来替换 Drawable 那么我们必须在 TextInputLayout 下面创建一个 TextView 以模拟错误消息。