2022-01-04 Databinding双向绑定用法

以spinner举例,首先定义一个在model


object SPModel : BaseObservable(){

    var pos = false

        @Bindable

        get(){

            return field

        }

        set(value){

            field = value

            notifyPropertyChanged(BR.pos)

        }

}

pos即spinner的selected position

然后给用BindingAdapter给spinner赋值


@JvmStatic

@BindingAdapter("selectedPos")

fun setSelectedPos(sp:Spinner,pos:Int){

    sp.setSelection(pos)

}

这个时候,当我们修改model的pos的值的时候,spinner的选中项就会变成对应position的项

然后需要对spinner进行反向绑定,即用 Databinding对onItemSelectedListener进行监听


@JvmStatic

@InverseBindingAdapter(attribute = "selectedPos",event = "posAttrChanged")

fun getSelectedPos(sp:Spinner){

    return sp.selectedItemPosition

}


@JvmStatic

@BindingAdapter("posAttrChanged")

fun setSPChanged(sp:Spinner,lis:InverseBindingListener){

    sp.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

            lis.onChange()

        }

        override fun onNothingSelected(parent: AdapterView<*>?) { }

    }

}

这个BindingAdapter对应的即是InverseBindingAdapter中的event,所以value需要与InverseBindingAdapter中的event一致

最后则是xml中添加属性,根目录添加 xmlns:bind="http://schemas.android.com/tools"


xmlns:bind="http://schemas.android.com/tools"



你可能感兴趣的:(2022-01-04 Databinding双向绑定用法)