<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harshal Kshatriya on Medium]]></title>
        <description><![CDATA[Stories by Harshal Kshatriya on Medium]]></description>
        <link>https://medium.com/@harshalkshatriya?source=rss-d8ddc4e82d56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*C0fAeUa1D9EMuywf.</url>
            <title>Stories by Harshal Kshatriya on Medium</title>
            <link>https://medium.com/@harshalkshatriya?source=rss-d8ddc4e82d56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:48:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshalkshatriya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Data Binding And ViewModels: In Perspective — PART 1]]></title>
            <link>https://medium.com/@harshalkshatriya/android-data-binding-and-viewmodels-in-perspective-part-1-88b47300b2a7?source=rss-d8ddc4e82d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b47300b2a7</guid>
            <category><![CDATA[android-jetpack]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-data-binding]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Harshal Kshatriya]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 06:18:33 GMT</pubDate>
            <atom:updated>2019-09-28T10:21:22.178Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Data Binding And ViewModels: In Perspective — PART 1</h3><p>To begin with, I would like to share a story with you all as to why I chose this topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTy7WcuSIyBz-gF35x6wHA.jpeg" /><figcaption>Photo: Komal Kshatriya</figcaption></figure><p>In 2017, we faced a problem. We could not find the right solution for the problem (expressed the way we wanted it). So we thought of building one. After doing all the groundwork, we started implementing the solution. That’s how we started AnnexTech. My co-founder started working on the back-end and I started work on the front-end. Soon the codebase on the front-end side started getting bloated. <strong>30–40% of the fragment was occupied by view declarations, gaining access and setting them.</strong> We have tens of fragments in our code. I started searching for ways to tackle the issue. I discovered Android Data Binding and ViewModels. As soon as I started using it, I instantly recognized its power and decided to make it an integral part of the project. The code became much more concise and readable. Putting myself in other developers’ shoes, I thought there may be others facing similar problems as me and hence, this talk. <strong>So these articles are actually a by-product of the innovation that we have done at AnnexTech.</strong></p><h4>A Railway Ticket</h4><p>Let’s understand these concepts with an example. Consider an App which just displays a Railway Ticket (Fig. 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M14qqqkxPknB9i6Bhngqyg.png" /></figure><p>The UI is divided into four parts:</p><ul><li><strong>Ticket Info</strong></li><li><strong>Fare Details</strong></li><li><strong>Journey Details</strong></li><li><strong>Passenger Info</strong></li></ul><p><strong>Ticket Info </strong>contains details such as PNR No, Train No, Transaction ID, and Quota.</p><p><strong>Fare details </strong>has Ticket Fare, GST charges and Total Fare. This layout can expand/collapse.</p><p><strong>Journey Details</strong> contains “From” and “To” stations and scheduled departure and arrival datetime.</p><p>Lastly, <strong>Passenger Details</strong> shows Passenger Name, Mobile No, Address and no. of people travelling together.</p><h4>Modules in the Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*ONQlCUylnJqXiKH1u4b2HQ.png" /><figcaption>Fig 3</figcaption></figure><h4>Traditional Way</h4><pre>private TextView mPNRText;<br>private TextView mTransactionIdText;<br>private TextView mTrainNoText;<br>private TextView mQuotaText;<br>...</pre><pre>mPNRText = view.findViewById(R.id.pnrNoText);<br>mTransactionIdText = view.findViewById(R.id.transactionIdText);<br>mTrainNoText = view.findViewById(R.id.trainNoText);<br>mQuotaText = view.findViewById(R.id.quotaText);<br>...</pre><pre>mPNRText.setText(String.valueOf(ticket.getPnrNo()));<br>mTransactionIdText.setText(String.valueOf(ticket.getTransactionId()));<br>mTrainNoText.setText(String.valueOf(ticket.getTrainNo()));<br>mQuotaText.setText(ticket.getQuota().name());<br>...</pre><h3>Problems developers face</h3><ul><li><strong>Unnecessary code in Fragments. </strong>30–40% of the fragment is occupied by view declarations, gaining access and setting them.</li><li><strong>Loss of productivity doing mundane tasks</strong></li><li><strong>No dynamism in layout files. </strong>Due to which custom views have to be created for simple UIs too.</li></ul><h3>Android Data Binding</h3><p>The data binding library allows you to bind your App’s data source to the UI. It is part of the Android Architecture Components, which in turn is part of Android Jetpack. Google launched Android Jetpack in 2018. Its purpose is to enable developers to build quality, data-driven apps with ease.</p><p>The instant benefit you are going to notice is — <strong>No more boilerplate. </strong>You will not have to declare and initialize member variables in your fragments. <strong>No more findViewById(). </strong>This really beneficial especially when working on long-term projects. The lines of code decrease and it gives more power to each line of code.</p><p>So when you are getting started, you can explore the Data Binding library in levels of increasing capability and sophistication, a step at a time and still derive significant value. The levels are:</p><p><strong>Beginner Level </strong>— Eliminate findViewById().</p><p><strong>Intermediate Level </strong>— Once you are familiar that, start using Custom Binding Adapters and Observability.</p><p><strong>Expert Level </strong>— Use Two-Way Data Binding.</p><h3>Introduction to MVC and MVVM in Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8IrRCK84fZ7Avbic4eDYQ.png" /><figcaption>Credit: <a href="https://www.simform.com/">https://www.simform.com</a></figcaption></figure><p>When building the App in a traditional way (using findViewById), MVC architectural design pattern is used by default.</p><p>MVC stands for Model-View-Controller.</p><p>The Model layer contains the REST APIs, Database APIs and the business logic of the application.</p><p>The View layer contains the XML files (layout files).</p><p>The Controller is your Activity/Fragment classes. It is responsible for making REST API calls or Database API calls to fetch the data for the application. It will gain access to the views and set them. It controls everything. Hence, the name. It glues the model to the UI.</p><p>There are few drawbacks to using MVC:</p><ol><li>The view is dependent on the Model and Controller.</li><li>There is redundant code in Activity/Fragment.</li><li>There is less code reusability.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Z25KGk_c0esUCJ5c7KtIw.png" /><figcaption>Credit: <a href="https://www.simform.com/">https://www.simform.com</a></figcaption></figure><p>When we start using Data Binding and ViewModels in our project. We shift from MVC to MVVM architectural design pattern.</p><p>The Model layer consists of REST APIs, Database APIs and the business logic of the application. It can also contain a DataManager for abstraction.</p><p>The View layer consists of XML files (layout files) and Activity/Fragment.</p><p>The ViewModel layer consists of the ViewModel. The View and ViewModel are linked through Data Binding library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*4qKsbWZYPRRUGOssAIw36A.png" /><figcaption>Credit: <a href="https://proandroiddev.com/">https://proandroiddev.com</a></figcaption></figure><p>So the Activity/Fragment makes a call to DataManager to fetch the data. Then the data is pushed to the ViewModel layer, which further pushes the data to the View layer. If there are any changes in the view properties due to user interaction, the ViewModel data changes and accordingly the Model is updated if required.</p><p>The benefits of MVVM are:</p><ol><li>The view is decoupled from the Model. It now depends on the ViewModel.</li><li>More code reusability as layout files are dynamic, because of data binding.</li><li>Makes unit testing easier.</li></ol><h3>ViewModels</h3><p>As the name suggests, it is the Model for the View. It is a class that holds data for the UI. It is life-cycle aware, meaning, it has scope throughout an activity life-cycle (Fig.1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*zsmVvA2U4IUYdvhO8fU31w.jpeg" /><figcaption>Fig. 1 LifeCycle of ViewModels (Credit - https://code.tutsplus.com)</figcaption></figure><p>This enables you to share data between fragments. ViewModels are part of MVVM (Model-View-ViewModel) Architectural design.</p><h3>Modules in the App — With Data Binding and ViewModels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OyxywcYCImUHLUlbJMYnw.png" /></figure><h3>To Start Using Data Binding</h3><p>First, enable data binding in the build.gradle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8e66eb71d94abf2335f41a7b2ae8ccf/href">https://medium.com/media/a8e66eb71d94abf2335f41a7b2ae8ccf/href</a></iframe><p>Then, add &lt;layout&gt; as wrappers to the &lt;ConstraintLayout&gt; in the layout resource file for the fragment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb9eb0955ccdb0d7f9c6f91595ed72c4/href">https://medium.com/media/eb9eb0955ccdb0d7f9c6f91595ed72c4/href</a></iframe><h4>One-way Data Binding</h4><pre>&lt;Element<br>    attribute=&quot;@{expression}&quot;<br>    ...<br>&lt;/Element&gt;</pre><h4>The Model</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfba3eee1ff4f843025190924c63ccf2/href">https://medium.com/media/dfba3eee1ff4f843025190924c63ccf2/href</a></iframe><h4>The ViewModel</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02d9f748b8ff3677e9860faccf3ad804/href">https://medium.com/media/02d9f748b8ff3677e9860faccf3ad804/href</a></iframe><p>If you look at Ticket (Model) and TicketViewModel (ViewModel), they both have almost same member variables, then why have two different classes? That’s because <strong>Model is data for the application </strong>(business logic) whereas <strong>ViewModel is the data for the UI</strong>. There are variables like <strong>isFareExpanded</strong> and <strong>nightModeChecked</strong> which are only related to the UI not the business logic of the application.</p><p>The ViewModel is linked to the layout through getters and setters. If you notice the data type of <strong>quota, </strong>it is <strong>Ticket.RailQuotas. </strong>However, in the ticket_fragment.xml, to display Quota, we need to convert it into <strong>String. </strong>That is done by:</p><pre>public String getQuota() {<br>    return quota.name();<br>}</pre><p>Similarly, to display scheduled arrival and departure datetime the following methods convert LocalDateTime to String:</p><pre>public String getSchDepDate() { <br>    DateTimeFormatter formatter = <br>           DateTimeFormatter.ofPattern(&quot;dd-MMM-yyyy HH:mm a&quot;);<br>    return schDepDate.format(formatter);<br>}</pre><pre>public String getSchArrDate() {<br>    /* Similar to getSchDepDate() */<br>}</pre><h4>The word “BIND”</h4><p>When we use the word “BIND”, it is being used in two contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*BlqnZ4h8QWv8YDQ9YE1TOQ.png" /></figure><h4>Getting Started With using Data Binding in Fragments</h4><p>After doing the above, to start setting views with data binding, you first need the get the binding object — mFragBinding;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75245aed6b7c0b557f9036553a571e23/href">https://medium.com/media/75245aed6b7c0b557f9036553a571e23/href</a></iframe><p>In <strong>onCreateView(), DataBindingUtil.inflate() </strong>is used to get the mFragBinding object. The setLifeCycleOwner() method is used to observe changes to the LiveData.</p><p><strong>NOTE: If this is not used the expand/collapse for Fare Details won’t work.</strong></p><h4>Setting Views</h4><p>Now you can directly bind data using view ids:</p><pre>mFragBinding.ticketInfoLayout.pnrNoText = pnrNo;<br>mFragBinding.ticketInfoLayout.trainNoText = trainNo;<br>mFragBinding.ticketInfoLayout.transactionIdText = tId;<br>...</pre><p>Here, ticketInfoLayout is the id of the ‘include’d layout, ticket_info.xml.</p><p>But the actual power of data binding is achieved when you use something like this:</p><pre>mFragBinding.setTicket(ticketViewModel);</pre><p>This one statement sets the entire UI of the application in our example. It binds the ViewModel to the View. But this method is not created by its own. You will have to declare variables in your layouts.</p><h4>Data Variables in Layouts</h4><p>To generate <strong>setTicket()</strong> method, the following is required in <strong>ticket_fragment.xml</strong>:</p><pre>&lt;data&gt;<br>   &lt;variable name=&quot;ticket&quot;<br>      type=&quot;ex.com.ticketexample.viewmodel.TicketViewModel&quot; /&gt;&lt;/data&gt;</pre><h4><strong>Passing variables to &lt;include&gt;</strong></h4><p>So, when setTicket(ticketViewModel) is used, the variable is made passed on the ticket_fragment.xml and from here we have to further pass on the variables to all the 4 layouts included in ticket_fragment.xml, using <strong>bind:ticket</strong> attribute.</p><pre>&lt;include<br>  android:id=&quot;@+id/ticketInfoLayout&quot;<br>  layout=&quot;@layout/ticket_info&quot;<br>  ...<br>  <strong>bind:ticket=&quot;@{ticket}&quot; </strong>/&gt;</pre><pre>&lt;include<br>  android:id=&quot;@+id/journeyDetailsLayout&quot;<br>  layout=&quot;@layout/journey_details&quot;<br>  ...<br>  <strong>bind:ticket=&quot;@{ticket}&quot;</strong>/&gt;</pre><pre>&lt;include<br>  android:id=&quot;@+id/passengerDetailsLayout&quot;<br>  layout=&quot;@layout/passenger_details&quot;<br>  ...<br>  <strong>bind:ticket=&quot;@{ticket}&quot;</strong> /&gt;</pre><pre>&lt;include<br>  android:id=&quot;@+id/fareDetailsLayout&quot;<br>  layout=&quot;@layout/fare_details&quot;<br>  ...<br>  <strong>bind:ticket=&quot;@{ticket}&quot; </strong>/&gt;</pre><h4><strong>Bind Data to Layout attributes</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2867fbacf702d4cf9f8ce686aae898d/href">https://medium.com/media/b2867fbacf702d4cf9f8ce686aae898d/href</a></iframe><p>To bind the PNR No to the TextView, the following data binding expression is used:</p><pre>&lt;TextView<br>  android:id=&quot;@+id/pnrNoText&quot;<br>  ...<br><strong>  android:text=&quot;@{String.valueOf(ticket.pnrNo)}&quot; </strong>/&gt;</pre><p><strong>ticket.pnrNo </strong>gets the pnrNo, but since its datatype is Long, it is converted using String.valueOf().</p><pre>&lt;TextView<br>  android:id=&quot;@+id/quotaText&quot;<br>  ...<br>  <strong>android:text=&quot;@{ticket.quota}&quot;</strong> /&gt;</pre><p><strong>ticket.quota</strong> makes a call to <strong>getQuota()</strong> in TicketViewModel.java.</p><p>This is One-Way data binding. If you are just getting started you can start with this. But, there are limitations to this article:</p><ol><li>You will not be able to expand/collapse Fare Details.</li><li>Won’t be able to compute the total sum of the ticket.</li><li>Night mode won’t work.</li></ol><p>To understand how to overcome these constraints, check out<strong> </strong><a href="https://medium.com/@harshalkshatriya/android-data-binding-and-viewmodels-in-perspective-part-2-99cf122c726b?source=friends_link&amp;sk=1e88e3c733df65e44585c4eea330a216"><strong>Android Data Binding and ViewModels — Part-2</strong></a><strong>.</strong></p><p><em>Special thanks to </em><strong><em>Mr. Raju Dodhiawala</em></strong><em>(</em><a href="http://twitter.com/rajudodhia"><em>@rajudodhia</em></a><em>) for his ideas and advice. These articles are based on the inputs provided by him.</em></p><h4>Source code</h4><p>You can check out the source code here: <a href="https://github.com/FireAndIce/ticket-databinding">https://github.com/FireAndIce/ticket-databinding</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b47300b2a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Data Binding And ViewModels: In Perspective — PART 2]]></title>
            <link>https://medium.com/@harshalkshatriya/android-data-binding-and-viewmodels-in-perspective-part-2-99cf122c726b?source=rss-d8ddc4e82d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/99cf122c726b</guid>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[android-data-binding]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Harshal Kshatriya]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 06:17:11 GMT</pubDate>
            <atom:updated>2019-09-28T10:22:34.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Data Binding And ViewModels: In Perspective — PART 2</h3><p>With Android Data Binding And ViewModels, the problems we are solving are:</p><p>1. Eliminate redundant code,</p><p>2. Increase productivity and</p><p>3. Make layout files more dynamic.</p><p><a href="https://medium.com/@harshalkshatriya/android-data-binding-and-viewmodels-in-perspective-part-1-88b47300b2a7?source=friends_link&amp;sk=35abf3e2b778f6ba243ae8ab5bd1538b"><strong>Android Data Binding and ViewModels: In Perspective — Part 1</strong></a> will introduce the example that we are using to demonstrate, in tackling these problems. It will also help you get familiar with the basics of One-Way Data Binding. It is a prerequisite to this part. It is recommended you read Part 1 first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PW8VUWJzVISP3lqDJCFqkw.jpeg" /><figcaption>Photo: Komal Kshatriya</figcaption></figure><p>In this Part-2 writeup, we are going to focus on:</p><ul><li>Custom Binding Adapters</li><li>Observability</li><li>Two-Way Data Binding</li></ul><h3>Custom Binding Adapters</h3><p>First, let’s understand what Binding Adapters are. They are attribute setters. They are responsible for making appropriate framework calls to set values.</p><p>For example, when</p><pre>android:text=&quot;@{text}&quot; </pre><p>is bound, the Binding Adapter makes a call to</p><pre>public final void setText(Charsequence text)</pre><p>But, what if you have a custom attribute?</p><pre>app:totalFareText=@{ticket}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDaMYWCF2lHCwqzukBecQQ.png" /></figure><p>That’s where Custom Binding Adapters come into the picture.</p><h4>Using Custom Binding Adapters</h4><p>In fare_details.xml, we have a custom attribute <strong>app:totalFareText</strong></p><pre><br>&lt;<strong>TextView</strong><br>    android:id=&quot;@+id/totalFareText&quot;<br>    ...<br>    app:<strong>totalFareText</strong>=&quot;@{<strong>ticket</strong>}&quot; /&gt;</pre><p>In TicketFragment.java, we have the following:</p><pre>@BindingAdapter(&quot;<strong>totalFareText</strong>&quot;)<br>public static void setTotalFare(<strong>TextView</strong> view,<br>                            <strong>TicketViewModel</strong> ticketViewModel) {<br>   Log.d(TAG, &quot;In computeTotalFare()&quot;);<br>   view.setText(String.valueOf(ticketViewModel.computeTotalFare()));<br>}</pre><p>The method name can be anything reasonable that you prefer but it should be annotated with the attribute name for which you are creating the Binding Adapter.<strong> </strong>Also, the first parameter, TextView in the above case, should be of the same type as the one in layout file. The second parameter, TicketViewModel, should be of the same type as the variable you are binding to the custom attribute in the layout file.</p><p>By doing this, the framework now knows which method to call to set the view for the attribute.</p><h3>Observability</h3><p>To build a high-quality app, it has to be very reactive. This can be achieved by using LiveData in ViewModels. LiveData helps you ensure the app UI matches with the state of the data. So if the data related to the UI changes, the UI changes accordingly. In this example, we are using Observability for Fare Details. With the help of it, we are able to expand/collapse the Fare Details view (without creating a custom view).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYqgFlPkqCLE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYqgFlPkqCLE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYqgFlPkqCLE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e105fffe06bd3a41aa598ad0a7afa9/href">https://medium.com/media/e6e105fffe06bd3a41aa598ad0a7afa9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff1dc0539b4abafa9989317e06dc2a1/href">https://medium.com/media/5ff1dc0539b4abafa9989317e06dc2a1/href</a></iframe><pre>&lt;TextView<br>    android:id=&quot;@+id/ticketFareText&quot;<br>    ...<br>    android:text=&quot;@{String.valueOf(ticket.ticketFare)}&quot;<br>    <strong>android:visibility=&quot;@{ticket.isFareExpanded ? View.VISIBLE : View.GONE}&quot;</strong> /&gt;</pre><pre>&lt;TextView<br>    android:id=&quot;@+id/gstText&quot;<br>    ...<br>    android:text=&quot;@{String.valueOf(ticket.gstCharge)}&quot;<br>    <strong>android:visibility=&quot;@{ticket.isFareExpanded ? View.VISIBLE : View.GONE}&quot;</strong> /&gt;</pre><p>The visibility of <strong>ticketFareText</strong> and <strong>gstText</strong> depends on the <strong>isFareExpanded</strong>. If it is true, the views are made VISIBLE else GONE. Now, when the user interacts with the expand/collapse icon, <strong>toggleFare()</strong> is called.</p><pre>/* Binds ExpandIcon with TRUE and sets toggle on it.    <br> * Without MutableLiveData the EXPAND/COLLAPSE WONT WORK */    private void bindExpandIcon() {<br>    ticketViewModel.isFareExpanded = new MutableLiveData&lt;&gt;();<br>    ticketViewModel.isFareExpanded.setValue(true); //DEFAULT VALUE<br>    <strong>mFragBinding.imageView.setOnClickListener(v -&gt; {<br>          ticketViewModel.toggleFare();<br>    });</strong><br>}</pre><pre><strong><br>public void toggleFare() {<br>    isFareExpanded.setValue(!isFareExpanded.getValue());<br>}</strong></pre><p>As the data for the UI, that is isFareExpanded, changes, the UI changes accordingly.</p><h3>Two-Way Data Binding</h3><p>What we saw up till now was One-Way Data Binding, any changes to ViewModel data is updated to the View. Two-Way Data Binding also allows any changes to the View to update the UI data. This can be helpful when the user is interacting with views in the app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwAJeNynOV1M%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwAJeNynOV1M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwAJeNynOV1M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/935c6872706640c68889b1bbe6924cef/href">https://medium.com/media/935c6872706640c68889b1bbe6924cef/href</a></iframe><h4>Using Two-Way Data Binding</h4><pre>&lt;android.support.constraint.ConstraintLayout<br>    android:id=&quot;@+id/main&quot;<br>    ...<br>    <strong>android:background=&quot;@{ticket.nightModeChecked ?@drawable/nightMode : @drawable/lightGray}&quot;</strong> &gt;</pre><pre>&lt;CheckBox<br>    android:id=&quot;@+id/nightModeCheckBox&quot;<br>    ...<br>    android:text=&quot;Night Mode&quot;<br>    <strong>android:checked=&quot;@={ticket.nightModeChecked}&quot;</strong> <br>    ...<br>/&gt;</pre><p>The syntax for Two-Way data binding is similar to One-Way data binding. The only difference is syntactical: <strong>“@={}”</strong>.</p><p>When the user checks the Night Mode, the nightModeChecked value (the UI data) is changed. Here, the UI is changing the data. As the data changes, the <strong>android:background</strong> changes accordingly.</p><p>This is a simple two-way data binding example.</p><p>I leave it to the readers to explore two-way data binding with custom binding adapters.</p><p><em>Special thanks to </em><strong><em>Mr. Raju Dodhiawala</em></strong><em>(</em><a href="http://twitter.com/rajudodhia"><em>@rajudodhia</em></a><em>) for his ideas and advice. These articles are based on the inputs provided by him.</em></p><h4>Source Code</h4><p>You can check out the source code here: <a href="https://github.com/FireAndIce/ticket-databinding">https://github.com/FireAndIce/ticket-databinding</a></p><h4>Sources</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoyVdrZsyxIw%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoyVdrZsyxIw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoyVdrZsyxIw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f6f4e1f1a54620665b153353878128d/href">https://medium.com/media/0f6f4e1f1a54620665b153353878128d/href</a></iframe><p><a href="https://developer.android.com/topic/libraries/data-binding">Data Binding Library | Android Developers</a></p><p><a href="https://www.simform.com/mvc-mvp-mvvm-android-app-development/">https://simform.com/mvc-mvp-mvvm-android-app-development/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99cf122c726b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>