I would like to enable a AppCompatButton when all fields in a form are complete.
I am using a ViewModel and would like to use Databinding to enable this.
I have 2 methods that fire when text is changed on the views to update an objects data in the viewmodel.
The issue I am running into is when both fields are complete, I need to enable a button on the layout allowing them to proceed.
An example would be log in, when the username and password fields are fulled in, the log in button becomes enabled.
You can use the same solution like here
But if you want use only AndroidArch and DataBinding you can create your own approach like below:
class MyVM : ViewModel() {
...
val mLoginLiveData = MutableLiveData<String>()
val mPasswordLiveData = MutableLiveData<String>()
val mLoginPasswordMediator = MediatorLiveData<Boolean>()
...
init {
mLoginPasswordMediator.addSource(mLoginLiveData) { validateForm() }
mLoginPasswordMediator.addSource(mPasswordLiveData) { validateForm() }
...
}
private fun validateForm() {
// put your validation logic here, and update the following value
// as `true` or `false` based on validation result
// mLoginPasswordMediator.value = ...
}
override fun onCleared() {
// DO NOT forget to remove sources from mediator
mLoginPasswordMediator.removeSource(mLoginLiveData)
mLoginPasswordMediator.removeSource(mPasswordLiveData)
}
}
and in your activity class listen your MediatorLiveData
:
class MyActivity : AppCompatActivity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
//Obtain your ViewModel class here
//Initialize binding here
...
mBinding.lifecycleOwner = this
mVM.mLoginPasswordMediator.observe(this, Observer { validationResult ->
mBinding.yourButton.isEnabled = validationResult
})
}
}
And didn't forget to use your LiveData
s' in 'your_activity_layout'.xml
:
...
//Add your ViewModel class to layout here
<EditText
...
android:text="@={vm.mLoginLiveData}"
... />
...
<EditText
...
android:text="@={vm.mPasswordLiveData}"
... />
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With