In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
What we are going to build in this article?
Here is a sample video of what we are going to build in this project. Note that we are going to make this project in Java language.
Step-by-Step Implementation
Step 1: Create a New Project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- Name the application at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2. Enable DataBinding
Navigate to Gradle Scripts > gradle.scripts(module) and add the following code to it.
buildFeatures
{
    dataBinding = true
}
Just followed the image and got it.
 
Step 3. Working on XML files
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
| <?xmlversion="1.0"encoding="utf-8"?>    <LinearLayout        android:layout_width="match_parent"        android:orientation="vertical"        android:padding="16dp"        android:layout_height="match_parent"        tools:context=".MainActivity">        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="Data Binding\nFor Activity"            android:textSize="24sp"            android:textStyle="bold"            android:textColor="@color/design_default_color_primary"            android:gravity="center"/>        <EditText            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:id="@+id/et_input"            android:hint="Enter text"            android:padding="12dp"            android:layout_marginTop="16dp"            android:background="@android:drawable/editbox_background"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/bt_submit"            android:text="Submit"            android:layout_gravity="center"            android:layout_marginTop="8dp"/>        <TextView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:id="@+id/tv_output"            android:textSize="32sp"            android:textStyle="bold"            android:gravity="center"            android:layout_marginTop="8dp"/>        <FrameLayout            android:layout_width="match_parent"            android:layout_height="match_parent"            android:id="@+id/fragment"            android:layout_marginTop="16dp"/>    </LinearLayout></layout> | 
Navigate to app > right-click > new > fragment > BlankFragment and name it as “MainFragement”. Use the following code in fragment_main.xml file:
XML
| <?xmlversion="1.0"encoding="utf-8"?>            <LinearLayout            android:layout_width="match_parent"            android:orientation="vertical"            android:gravity="center_horizontal"            android:layout_height="match_parent"            tools:context=".MainFragment">                <TextView                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="Data Binding\nFor Fragment"                android:textSize="24sp"                android:textStyle="bold"                android:textColor="@color/design_default_color_primary"                android:gravity="center"/>                <EditText                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:id="@+id/et_input"                android:hint="Enter text"                android:padding="12dp"                android:layout_marginTop="16dp"                android:background="@android:drawable/editbox_background"/>                <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:id="@+id/bt_submit"                android:text="submit"                android:layout_marginTop="8dp"/>                <TextView                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:id="@+id/tv_output"                android:textSize="32sp"                android:textStyle="bold"                android:gravity="center"                android:layout_marginTop="8dp"/>            </LinearLayout></layout> | 
Step 4. Working on Java files
Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.
Java
| packagecom.example.databinding;importandroidx.appcompat.app.AppCompatActivity;importandroidx.databinding.DataBindingComponent;importandroidx.databinding.DataBindingUtil;importandroidx.fragment.app.Fragment;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Toast;importcom.example.databinding.databinding.ActivityMainBinding;publicclassMainActivity extendsAppCompatActivity {    // Initialize variables    ActivityMainBinding binding;    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // Assign variable        binding= DataBindingUtil.setContentView(this,R.layout.activity_main);        binding.btSubmit.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View view) {                // Get text from edit text                String sText=binding.etInput.getText().toString().trim();                // Check condition                if(!sText.equals(""))                {                    // when text is not empty                    // set text on text view                    binding.tvOutput.setText(sText);                }                else                {                    // When text is empty                    // Display Toast                    Toast.makeText(getApplicationContext()                    ,"Please enter text",Toast.LENGTH_SHORT).show();                }            }        });        // Initialize fragment        Fragment fragment=newMainFragment();        // Commit fragment        getSupportFragmentManager().beginTransaction()                .replace(R.id.fragment,fragment).commit();    }} | 
Navigate to the MainFragment.java file and use the following code in it. Comments are added to the code to have a better understanding.
Java
| packagecom.example.databinding;importandroid.os.Bundle;importandroidx.databinding.DataBindingUtil;importandroidx.fragment.app.Fragment;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.Toast;importcom.example.databinding.databinding.FragmentMainBinding;publicclassMainFragment extendsFragment {    // Initialize variable    privateFragmentMainBinding binding;    privateView view;    privatestaticfinalString ARG_PARAM1 = "param1";    privatestaticfinalString ARG_PARAM2 = "param2";    privateString mParam1;    privateString mParam2;    publicMainFragment() {    // Required empty public constructor    }    publicstaticMainFragment newInstance(String param1, String param2) {        MainFragment fragment = newMainFragment();        Bundle args = newBundle();        args.putString(ARG_PARAM1, param1);        args.putString(ARG_PARAM2, param2);        fragment.setArguments(args);        returnfragment;    }    @Override    publicvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        if(getArguments() != null) {            mParam1 = getArguments().getString(ARG_PARAM1);            mParam2 = getArguments().getString(ARG_PARAM2);        }    }    @Override    publicView onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Assign variable        binding= DataBindingUtil.inflate(inflater,R.layout.fragment_main,container,false);        view=binding.getRoot();        binding.btSubmit.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View view) {                // Get text from edit text                String sText=binding.etInput.getText().toString().trim();                // Check condition                if(!sText.equals(""))                {                    // When text is not empty                    // Set text on text view                    binding.tvOutput.setText(sText);                }                else                {                    // When text is empty                    // Display Toast                    Toast.makeText(view.getContext(),                            "Please enter text",Toast.LENGTH_SHORT).show();                }            }        });        // Return view        returnview;    }} | 
Here is the final output of our application.
Output:


 
                                    







