We are all familiar with the findVIewById() method but it is a costly operation for applications. Each and every time we try to do findVIewById() that particular view is being searched in the view hierarchy during runtime which is a time consuming process and it can slow the application for the user.
To fix it we can go with Data Binding. Data Binding allows us to connect to a layout to an activity or fragment at compile time. The compiler generates a helper class called a binding class when an activity/fragment is created and then by using that binding class object we can access views easily and perform operations on it.
Dependencies:
To enable data binding in our project add below lines in our app level gradle
android {
...
buildFeatures {
dataBinding true
}
}
How to implement:
Use better pointers
- Surround the layout xml code in <layout></layout> and add the namespace declarations to the tag.
Ex:
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/score_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
- Get a data binding object in our activity/fragment by calling
DataBindingUtil.setContentView() for activity DataBindingUtil.inflate() for fragment.
val dataBindingObject = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
Note: Let’s say the name of the activity is MainActivity then the binding class for the activity will be ActivityMainBinding.
- Now by using the binding object we can call the views directly.
Ex:
dataBindingObject.scoreText = View.VISIBLE
class MyScoreDetailsFragment : Fragment()
{
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val binding: MyScoreDetailsFragment = DataBindingUtil.inflate(inflater, R.layout.myscoredetails_fragment, container, false)
binding.scoreText.text = "score"
return binding.root
}
}
Basically with data binding enabled the compiler creates a reference to all views in a <layout></layout> that have an id and gathers them in a binding object and then we just use the object to perform operations on them.