Get rid of findViewById()!

Today we will see how to get rid of findViewById in android. There is no third party library is needed for this. It can be done easily by using default databinding in android.

Step 1: To do this first open you app level gradle file. Then add data binding enabled true in android block.

android {
    .
    .
    .
    dataBinding {
        enabled true
    }
}

Step 2: Here you need to work with your xml layout. You have to put all the xml code inside a root <layout> tag. Ex:

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activity.tailor.CartActivity">

       <Button
          android:id="@+id/bt_order_selector"
          android:paddingRight="@dimen/_6sdp"
          android:paddingLeft="@dimen/_6sdp"
          android:textColor="@color/white"
          android:text="Select Date"
          android:background="@drawable/rounded_text"
          android:layout_width="wrap_content"
          android:layout_height="@dimen/_30sdp" />

    </android.support.design.widget.CoordinatorLayout>
</layout>


Now rebuild your project. Your databinding class will be automatically created.

Step 3: Now open your activity class. Take a variable of which type will be the name of your xml ending with binding file. For example, if your xml file name is activity_main then you find a class ActivityMainBinding. You need to create an object of this class. And after that you need to initialise this object by editing the setContentView like this:

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

Step 4: Awesome, You are done. Now you can access your view widgets by their id. It will return the same view object as it would return by findviewbyid.

binding.btOrderSelector.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
        });

If you are not clear enough, please comment bellow.