簡體   English   中英

Android 雙向綁定 Integer 類型問題

[英]Android two way binding Integer type issue

當我想使用數據綁定方法從 XML 傳輸數據以查看 model class class 時遇到問題。 我已經看到了很多與此相關的問題,但我嘗試過的解決方案還沒有。 這是什么原因?

XML

      <EditText
        android:id="@+id/editTextTextPersonName3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="30dp"
        android:ems="10"
        android:hint="Telefon"
        android:inputType="textPersonName"
        app:layout_constraintBaseline_toBaselineOf="@+id/editTextTextPersonName2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/editTextTextPersonName2"
        android:text="@={`` +addTenant.tc}"/>

查看 Model

class AddTenantVM(application: Application): BaseViewModel(application) {
    val tc = MutableLiveData<Int>()

    fun tenant (){
        println(tc.value.toString())
    }
}

由於您的 MutableLiveData 是 Integer 類型,因此編輯文本應該獲得 integer 輸入類型。 嘗試使用: android:inputType="phone"android:inputType="numberDecimal" 還要在視圖 model 中初始化可變實時數據。 像這樣val tc = MutableLiveData<Int>(0)

默認情況下,當您傳遞一個 int 時,它會嘗試搜索相同的字符串資源。 R.string.example_string實際上是一個int

並且通過放置 `` + (int),2-way 綁定功能將丟失 - 因為綁定器不知道如何轉換它。

解決方法:將下面的代碼放在一個單獨的.kt文件中(我已經創建了CustomBindings.kt並放置了)。 不需要 Class - 直接粘貼函數即可。

@BindingAdapter("my_number")
fun setNumber(view: TextView, value: Int?) {
    if (view.text != value)
        view.text = "" + value
}

@InverseBindingAdapter(attribute = "my_number")
fun getNumber(view: TextView): Int {
    return view.text.toString().toIntOrNull() ?: 0
}

在 XML 中,刪除 android:text 並輸入:

app:my_number="@={addTenant.tc}"

================= 下面的可選步驟 =======================

此外,如果您遇到任何錯誤,例如 my_numberAttrChange 未定義,請將其放入 CustomBindings.kt

@BindingAdapter(value = ["my_numberAttrChanged"])
fun setListener(textView: EditText, numberAttrChanged: InverseBindingListener?) {
    if (numberAttrChanged!= null) {
        textView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, start: Int, end: Int) {
// this will change as per your app's behavourial requirements
                if (start != end) {
                    numberAttrChanged.onChange()
                }
                textView.setSelection(end)
            }

            override fun afterTextChanged(editable: Editable) {
            }
        })
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM