Button state based on the validation

Sanjay Kakadiya
Droid by me
Published in
2 min readJun 18, 2020

--

We may come across such a requirement like a button should be disabled if the validations of the form are failed. Today, I am going to explain how we can manage button state(i.e. enable or disable) base on form validation using MVVM architecture in Kotlin.

So let’s start how we can achieve this.

Let’s first develop XML. I will just add EditText and Button in this example.

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:text="@={viewmodel.emailAddress}" //<----Don't forgot
android:inputType="textEmailAddress" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="@{viewmodel.valid}" //<----Don't forgot
android:text="@string/save"
android:textAllCaps="true"/>

Now let’s setup ViewModel.

class MainViewModel() : ViewModel() {    val emailAddress = MutableLiveData("")
val valid = MediatorLiveData<Boolean>().apply {
addSource(emailAddress) {
value = isValid()
}
}
private fun isValid(): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(emailAddress.value!!).matches()
}
}

Final step. Let’s bind our ViewModel with Activity. For that see below code. I used the kodein framework for dependency injection.

class TestActivity : AppCompatActivity(), KodeinAware{
override val kodein by kodein()
private val factory: MainViewModelFactory by instance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

var binding: ActivityTestBinding =
DataBindingUtil.setContentView(this, R.layout.activity_test)
val viewModel = ViewModelProvider(this, factory).get(MainViewModel::class.java)
binding.viewmodel = viewModel
binding.lifecycleOwner = this

That’s it. Now test the code. You can see the button state. By default, it’s disabled. It will enable if you will enter a valid email id.

You can download code from the GitHub repository.

If you liked this post, kindly give me some claps and follow me for more posts like this one. Be sure to leave a comment if you have any thoughts or questions.

--

--