Android-Basic Data Binding

Any android developer while developing an app will come across multiple scenarios where they to reference UI elements they put this very long code that contains “findViewById” .

This is frustrating as you have to type these long statements again and again for every element that you use.

Things like Butterknife do make things a bit easier but then again we need to reference R.id.ohmygod for each element.

But Google now gives us a way in which we can use the id in a more generic name and do operations on it without using R.id !

So the concept of data binding is really simple. First thing you need to enable data binding in your project.

Head over to your app’s build.gradle file and under the android {} section enter this

dataBinding.enabled = true

Now create a project. I let google name my default activity class and res file (MainActivity,activity_main)

Second we need to create a data binding object. This object if has to access the UI elements of a res file say activity_main then the object will be of type ActivityMainBinding

it camel cases the res file name and adds Binding. So if it’s a file hello_world then the object will be HelloWorldBinding

So we create the object like this

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

Now I edit my res file to have two text fields

<layout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/section"
/>
</LinearLayout>
</layout>

Notice the <layout> tags. These are important if you are using Data Binding. Please dont forget them as this indicates that this res file needs some kind of processing to be done.

Now to access the name and section I dont type a “findViewByID”

To access and set the text I simply put

binding.name.setText("Sidhanth");
binding.section.setText("CSE COOL");

That’s all there is folks !

My complete Main activity file is

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.name.setText("Sidhanth");
binding.section.setText("CSE C");
}
}