【发布时间】:2018-01-16 15:32:25
【问题描述】:
我正在使用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
}
我的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>
我想做什么
我想在错误文本右侧的错误/提示文本(感叹号三角形)中放置一个图标。
我的尝试
尝试 1
I found an implementation 使用 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"
但这不会渲染drawable,只是资源路径的字符串。
尝试 2
我发现another one 覆盖了TextInputLayoutHelper,以便在文本旁边设置一个drawable。如您所见,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)
}
是否有替代或内置“Android 方式”将此图标添加到错误/提示文本旁边?
【问题讨论】:
-
把所有的edittext放在一个框架布局中并在它上面放一个视图怎么样?
-
@UrielFrankel 对于这样的实现,我唯一的犹豫是我想通过使用
app:errorEnabled和app:errorTextAppearance来控制样式/位置来坚持“原生 Android”的做事方式我的错误。每当我想使用图标时,我都不想担心定位我的错误文本。但这绝对是解决我遇到的这个问题的有效方法,谢谢!
标签: android kotlin android-drawable