gpt4 book ai didi

data-binding - Kotlin 2路绑定(bind)自定义 View

转载 作者:行者123 更新时间:2023-12-02 12:12:08 25 4
gpt4 key购买 nike

我有 1 个自定义 View ,它扩展了 ConstraintLayout 并包含 1 个 EditText 和 2 个 TextViews

在我的自定义 View 中,我定义了这个 attr (和其他):

<attr name="Text" format="string" />

我像这样使用它:
app:Text="@={login.email}"

在我的自定义 View 中,我定义:
  companion object {
@JvmStatic @BindingAdapter("Text")
fun setText(nMe : View, nText: String) {
nMe.nInput.setText(nText)
}
@InverseBindingAdapter(attribute = "Text")
fun getText(nMe : View) : String {
return nMe.nInput.text.toString()
}

女巫在单向绑定(bind)中工作正常
app:Text="@{login.email}"

但是当我尝试在双向绑定(bind)中使用它时,我得到指向 ActivityLoginBinding.java java.lang.String callbackArg_0 = mBindingComponent.null.getText(mEmail); 的错误。

怎么做才能获得2路绑定(bind)?

:经过一些研究,我最终得到了这个:
@InverseBindingMethods(InverseBindingMethod(type = 
CustomInput::class,attribute = "bind:Text",event =
"bind:textAttrChanged",method = "bind:getText"))
class CustomEditTextBinder {
companion object {
@JvmStatic
@BindingAdapter(value = ["textAttrChanged"])
fun setListener(editText: CustomInput, listener: InverseBindingListener?) {
if (listener != null) {
editText.nInput.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

}

override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

}

override fun afterTextChanged(editable: Editable) {
listener.onChange()
}
})
}
}

@JvmStatic
@InverseBindingAdapter(attribute = "Text")
fun getText(nMe: CustomInput): String {
return nMe.nInput.text.toString()
}

@JvmStatic
@BindingAdapter("Text")
fun setText(editText: CustomInput, text: String?) {
text?.let {
if (it != editText.nInput.text.toString()) {
editText.nInput.setText(it)
}
}
}
}

}

但现在我得到:
找不到事件 TextAttrChanged

最佳答案

我想你只需要event = "android:textAttrChanged" .
这对我有用(将文本设置为空 String 如果它是 0):

object DataBindingUtil {
@BindingAdapter("emptyIfZeroText")
@JvmStatic
fun setText(editText: EditText, text: String?) {
if (text == "0" || text == "0.0") editText.setText("") else editText.setText(text)
}

@InverseBindingAdapter(attribute = "emptyIfZeroText", event = "android:textAttrChanged")
@JvmStatic
fun getText(editText: EditText) = editText.text.toString()
}

关于data-binding - Kotlin 2路绑定(bind)自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52063206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com