Reputation: 21
I need to create a Login Activity
in an Android app using Data Binding with ViewModel
using Kotlin. I want to enable/disable a Button based on the content of an EditText
field. The expected behavior that I'm trying to achieve is the button should get enabled only when none of theEditText
fields is empty.
Upvotes: 1
Views: 2618
Reputation: 1636
Step 1: In ViewModel
declare
var isEnabled : ObservableBoolean? = null
and initialize it in init
block.
Step 2: Set value of isEnabled
in your Text Change Listener like
isEnabled?.set(!isLoginFormValid())
Step 3: bind variable in xml
file like
android:enabled="@{viewmodel.isEnabled}"
Upvotes: 3
Reputation: 443
Add a boolean MediatorLiveData in your ViewModel and bind this to the enabled attribute of the button.
You should have MutableLiveData fields that's two-way bound to your EditTexts. Add these as MutableLiveData as sources to the boolean MediatorLiveData so that it can observe changes to the EditTexts as user enters values.
Add whatever logic in the MediatorLiveData observers to set it's value to true/false depending on whatever logic you want (e.g. values of the EditTexts should not be null or empty)
Upvotes: 1
Reputation: 171
you can put validations in the on click method of the login button.like:-
if(edittext_one!=null){then do the code here for the onclick }
like this you can put as much validations as you want on the edittext using if else statements.i hope this helps
Upvotes: 0