i尝试使myEdittext扩展EditText类只有一个更改:没有显示错误的"工具提示"。仅显示Edittext.Error ="一些错误"
时显示图标(!(class MyEditText : EditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun setError(error: CharSequence, icon: Drawable) {
setCompoundDrawables(null, null, icon, null)
}
}
当我在Anko DSL中使用
editText {
id = editNameId
}
,在代码中,我尝试了演员:
private lateinit var editName: MyEditText
editName = find<MyEditText>(editNameId)
// or other variants
// editName = find<EditText>(editNameId)
// editName = find<EditText>(editNameId) as MyEditText
我的错误无法将Edittext扔到myEdittext上。如果我正确理解,我需要将自己的小部件标签制作到Anko。
myEditText {
id = editNameId
}
我发现应该使用类似的代码:
inline fun ViewManager.myEditText() = myEditText {}
inline fun ViewManager.myEditText(theme: Int = 0, init: MyEditText.() -> Unit) = ankoView({MyEditText(it)}, theme, init)
这是不起作用的,因为我不知道如何将两个参数传递给构造函数:上下文和attrs。
我已经考虑了很长时间了,我无法解决;/
谢谢您的时间。
我相信您想使您的视图类从DSL访问,然后明确创建。
将此代码添加到包含您自定义视图类的文件:
inline fun ViewManager.myEditText(init: MyEditText.() -> Unit): MyEditText {
return ankoView({ MyEditText(it) }, theme = 0, init = init)
}
然后,您可以在Anko DSL中使用以下内容: myEdittext {id = editnameid}
另一个建议的更改是不使用视图ID,而只是从DSL分配一个变量:
verticalLayout {
editName = myEditText {}
}
我做了最终解决方案:
extension.kt
class MyEditText : EditText {
var isError = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun setError(error: CharSequence?, icon: Drawable?) {
setCompoundDrawables(null, null, icon, null)
isError = error != null
} }
inline fun ViewManager.myEditText(theme: Int = 0, init: MyEditText.() -> Unit) = ankoView({MyEditText(it)}, theme, init)
在Anko DSL类中(eTname在companion对象中定义(
myEditText {
id = etName
}
活动
private lateinit var enterName: MyEditText
[..]
override fun onCreate [...]
{
enterName = find(etName)
if (enterName.text.isNotEmpty()) enterName.error = null else enterName.error = "error"
enterName.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
if (s!!.isNotEmpty()) enterName.error = null else enterName.error = "error"
validateForm()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
validateForm()
// rest of onCreate
}
private fun validateForm() {
editButton.isEnabled = enterName.isError == false
}