Android Components investigation – part 2 – ViewModel + Lifecycle that’s time really

In this short post I’ll fix the problem, occurred during writing previous article (it is no official way to connect data binding and ViewModel)- that’s time we will use android components to store screen state during phone rotation. To implement this, I removed databinding library from my project and add live data libraries instead. It is needed to mention that activity layout file was changed also – databinding root layout is removed. To connect xml-views with activities I’ll use popular butter knife library, so it is added into my project also.

Now view model of login screen looks a little bit different from the previous implementation:

It extends  android.arch.lifecycle.ViewModel class and have one public property – isConditionAccepted, which is MutableLiveData type (with the false initial value). Pretty simple 🙂

To support lifecycle owner functionality appropriate activity should  extend  android.arch.lifecycle.LifecycleActivity . The full code of the activity is

The key moment here is constructing view model via usage of ViewModelProvider and subscribing to the isConditionAccepted value change to enable\disable login button. After that all we need is to cha[the_ad_placement id=”below-post-headline”]nge isConditionAccepted property according to check box state. As the result – we achieve desired screen behaviour – login button is enabled only if we mark agreement checkbox and that state is stored on screen rotation:

As always – all code can be found on the my github page.

Leave a Reply