此按钮的禁用与绑定表达式的使用一起正常工作,但当它很长时,我需要将它移动到ViewModel中的一个方法,即它不能正常工作的地方。
<com.google.android.material.button.MaterialButton
android: id = "@ + id / btValidateLegalRepresentativeCE"
style = "@ style / BasicMaterialButton"
android: layout_width = "match_parent"
android: layout_marginTop = "21dp"
android: enabled = "@ {viewModel.documentLiveData.length()> 0 & viewModel.firstNameLiveData.length()> 0 & viewModel.lastNameLiveData.length()> 0} "
从ViewModel 调用方法
<com.google.android.material.button.MaterialButton
android: id = "@ + id / btValidateLegalRepresentativeCE"
style = "@ style / BasicMaterialButton"
android: layout_width = "match_parent"
android: layout_marginTop = "21dp"
app: enabled = "@ {viewModel.isValidate()}" />
ViewModel
private val _documentLiveData = MutableLiveData("")
val documentLiveData: MutableLiveData<String> get() = _documentLiveData
private val _firstNameLiveData = MutableLiveData("")
val firstNameLiveData: LiveData<String> get() = _firstNameLiveData
private val _lastNameLiveData = MutableLiveData("")
val lastNameLiveData: LiveData<String> get() = _lastNameLiveData
fun isValidate(): Boolean {
val document = documentLiveData.value?.length ?: 0
val firstName = firstNameLiveData.value?.length ?: 0
val lastName = lastNameLiveData.value?.length ?: 0
return (document > 0) && (firstName > 0) && (lastName > 0)
}
我认为以下几点:
binding.viewModel = viewModel
binding.lifecycleOwner = this
谢谢你的帮助。
要调用viewmodel中的函数,需要使用((->
app:enabled = "@ {()->viewModel.isValidate()}
如果上述方法不起作用,请创建自定义绑定适配器。
在java中,它将像一样
@androidx.databinding.BindingAdapter("android:viewModel")
public static void setButtonEnable(Button button,YourViewModel viewModel) {
if(viewModel.isValidate())
//if true ,enable button
button.setEnable(true);
else
//disable button
button.setEnable(false);
}
从布局中调用此自定义适配器,并将视图模型传递到适配器中。
<com.google.android.material.button.MaterialButton
android: id = "@ + id / btValidateLegalRepresentativeCE"
style = "@ style / BasicMaterialButton"
android: layout_width = "match_parent"
android: layout_marginTop = "21dp"
android:viewModel= "@{viewModel}" />