Guide to Android Data Binding

yogeshpaliyal

Yogesh Choudhary Paliyal

Posted on September 2, 2021

Guide to Android Data Binding

What is Data Binding?

It is a technique to connect Data with your views.

How it works?

It generates a java file that connects your views with the data.

Setting up project for Data Binding

build.gradle(:app)

plugins {
    ...
    id 'kotlin-kapt'
}

android {

    ...

    buildFeatures{
        dataBinding = true
    }
}
...

Enter fullscreen mode Exit fullscreen mode

Getting Started with the code

To add data binding wrap your parent view/view group with the <layout> tag

<layout> tag contains 2 sections <data> and your parent view group.

<data> tag can contain 2 more tags, <import> & <variable>, as the name shows import is used to import the dependencies like class, interface, etc. And variable used to declare variables that we can use in our layout file (later in this post).

Our hierarchy looks like this.

activity_main.xml

<layout>
     <data>

         <import name="com.sample.MyViewModel" />

         <variable 
                name="mViewModel"
                type="MyViewModel" />

     </data>

     <FrameLayout>
         ..............
     </FrameLayout>
</layout>
Enter fullscreen mode Exit fullscreen mode

Setup binding in Activity

class MainActivity: AppCompatActivity() {

       private lateinit var binding : ActivityMainBinding

        override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate(savedInstanceState)
              binding = ActivityMainBinding.inflate(layoutInflater)
              setContentView(binding.root)
              // start using the binding
        }

}
Enter fullscreen mode Exit fullscreen mode

Note: **ActivityMainBinding* is an auto-generated file, the file name will be based on your XML file, (not the activity or fragment file) *

Setup binding in Fragment

class SampleFragment : Fragment() {

    private  lateinit var binding: FragmentSampleBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentSampleBinding.inflate(inflater, container, false)
        return binding.root
    }

}
Enter fullscreen mode Exit fullscreen mode

Assign value to XML variables

binding.mViewModel = mViewModel

// adding lifecycler owner to binding to use live data inside your XML
// this refer to lifecycler owner in Activity
binding.lifecycleOwner = this

// use viewLifecycleOwner to get lifecyclerOwner for Fragment, Bottomsheet, Dialog, etc.
binding.lifecycleOwner = viewLifecycleOwner 

// this will do the pending binding things
binding.executePendingBindings()
Enter fullscreen mode Exit fullscreen mode

Handle Variable inside the Data Binding

To use variables in XML you have to wrap your value inside @{YOUR-VALUE}

<TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@{mViewModel.username}" />
Enter fullscreen mode Exit fullscreen mode

Handle interface inside the Data Binding

<TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@{()->mViewModel.yourFunction()}" />
Enter fullscreen mode Exit fullscreen mode

Note: you can also get the reference of current view by

(view) -> mViewModel.yourFunction(view)

Default values and Null safety

Default value is used to show in the preview

 android:text="@{mViewModel.name, default =`Default Value` }"
Enter fullscreen mode Exit fullscreen mode

Handle null variables ??

android:text="@{mViewModel.name ?? `Nullable Value`}"
Enter fullscreen mode Exit fullscreen mode

If mViewModel or name is null or not assigned then TextView will show 'Nullable Value'

Resource Reference

Dimen

android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"
Enter fullscreen mode Exit fullscreen mode

String & plurals

android:text="@{@string/nameFormat(firstName, etFirstName.text)}"
android:text="@{@plurals/banana(bananaCount)}"
Enter fullscreen mode Exit fullscreen mode

etFirstName is an edit text in the same layout file

Passing variables to included layout

sample_layout.xml
<layout>
               <data>
                   <variable 
                       name="customTitle"
                       type="String" />
               </data>
            ....
</layout>
Enter fullscreen mode Exit fullscreen mode
main_layout.xml
<include
       app:customTitle="@{`Test Title`}"
       ...
      />
Enter fullscreen mode Exit fullscreen mode

Note: You must provide value in @{} if you want to send the value as a variable

Thank you, guys.

Keep learning, Keep Sharing ❤️

Original post on yogeshpaliyal.com

💖 💪 🙅 🚩
yogeshpaliyal
Yogesh Choudhary Paliyal

Posted on September 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related