Spinner Selected Item 的双向数据绑定

Two Way Databinding For Spinner Selected Item

我有一个视图模型,它有一个字段 district,它是 MutableLiveData<String> 的类型 我已经用 var district = MutableLiveData<String>("") 初始化了它 我想为此将所选项目绑定到它我有一个 BindingClass

object SpinnerBindingUtil {
        @BindingAdapter(value = ["selectedValue", "selectedValueAttrChanged"], requireAll = false)
        fun bindSpinnerData(
        pAppCompatSpinner: Spinner,
        newSelectedValue: String,
        newTextAttrChanged: InverseBindingListener
        ) {
    pAppCompatSpinner.onItemSelectedListener = object : OnItemSelectedListener {
        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View,
            position: Int,
            id: Long
        ) {
            newTextAttrChanged.onChange()
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {}
    }
    if (newSelectedValue != null) {
        val pos =
            (pAppCompatSpinner.adapter as ArrayAdapter<String?>).getPosition(
                newSelectedValue
            )
        pAppCompatSpinner.setSelection(pos, true)
    }
}

@InverseBindingAdapter(attribute = "selectedValue", event = "selectedValueAttrChanged")
fun captureSelectedValue(pAppCompatSpinner: AppCompatSpinner): String {
    return pAppCompatSpinner.selectedItem as String
}

}

这是我的 xml

                    <Spinner
                    selectedValue="@= 
                    {addConsumerViewModel.district}"
                    android:entries="@array/districts"
                    android:id="@+id/districtSpinner"
                    style="@style/AddConsumerSpinner"/>

但是我收到错误我该如何解决这个问题

kotlin 中,您必须使用 kapt 才能正确处理数据绑定。在您的模块级别 build.gradle 应用此插件。

apply plugin: 'kotlin-kapt'

之后您可能会遇到 error: expected 类型问题。然后通过删除 object SpinnerBindingUtil {}:

让你的绑定适配器像简单的 kt 文件
@BindingAdapter(value = ["selectedValue", "selectedValueAttrChanged"], requireAll = false)
fun bindSpinnerData(
    pAppCompatSpinner: Spinner,
    newSelectedValue: String,
    newTextAttrChanged: InverseBindingListener
) {
    pAppCompatSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View,
            position: Int,
            id: Long
        ) {
            newTextAttrChanged.onChange()
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {}
    }
    if (newSelectedValue != null) {
        val pos =
            (pAppCompatSpinner.adapter as ArrayAdapter<String?>).getPosition(
                newSelectedValue
            )
        pAppCompatSpinner.setSelection(pos, true)
    }
}

@InverseBindingAdapter(attribute = "selectedValue", event = "selectedValueAttrChanged")
fun captureSelectedValue(pAppCompatSpinner: AppCompatSpinner): String {
    return pAppCompatSpinner.selectedItem as String
}