Data binding in Android is one of the most effective features for Android developers to bind the UI controls present in the layout with the data resources in the code. This makes the code less complicated and readable thus enhancing the overall maintainability of the application. In this article, I will be explaining what data binding is; how to implement it in Android for activities, views and fragments via Java and Kotlin.
Data Binding AndroidData binding is a process of linking the user interface of an application with its business objectives. The feature means that the UI components can be bound to the data source so the program does not require the developers to write a large amount of code on their own. This feature is quite handy in Android where it assists in alleviating the process of repopulating the UI from models or view models.
Setting Up Data Binding in Your ProjectBefore using data binding, you need to enable it in your project. Here’s how you can do it:
1. Add Data Binding Dependency: In your build. gradle (app level), add the following:
android { ... dataBinding { enabled = true } } 2. Sync Your Project: Make sure to sync your project after adding the dependency.
Data Binding in ActivitiesUsing data binding in activities involves a few simple steps. Let’s walk through an example:
1. Create a Layout File First, create a layout file and wrap your root layout with <layout> tags. This is necessary for data binding.
XML
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.example.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.name}" />
<TextView
android:id="@+id/ageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(user.age)}" />
</LinearLayout>
</layout>
2. Create the Activity Class
In your activity class, initialize the data binding object and set the data.
Java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import com.example.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user = new User("John Doe", 30);
binding.setUser(user);
}
}
Kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val user = User("John Doe", 30)
binding.user = user
}
}
Data Binding in FragmentsData binding in fragments follows a similar pattern to activities. Here’s a brief example:
1. Create a Fragment LayoutWrap the layout with <layout> tags and define the data variable.
XML
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="product"
type="com.example.Product" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/productNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{product.name}" />
<TextView
android:id="@+id/productPriceTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(product.price)}" />
</LinearLayout>
</layout>
2. Create the Fragment Class
Initialize the data binding object in the fragment.
Java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import com.example.databinding.FragmentProductBinding;
public class ProductFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
FragmentProductBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_product, container, false);
Product product = new Product("Laptop", 1000);
binding.setProduct(product);
return binding.getRoot();
}
}
Kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.example.databinding.FragmentProductBinding
class ProductFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: FragmentProductBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_product, container, false)
val product = Product("Laptop", 1000)
binding.product = product
return binding.root
}
}
Benefits of Data Binding- Reduced Boilerplate Code: Data binding helps in reducing the amount of code to be written by establishing a connection between the UI elements and the data and hence does not require to be rewritten again and again. This yields to improved code quality with less clutter and hence, less work to be done by developers.
- Improved Readability: Data Binding thus improves the overall quality and sends business code mixed with UI code thus improving the code readability. In large projects, it helps in comprehension and eradication, since the UI and the data are two different structures.
- Automatic Updates: Data binding can automatically set the UI when data changes for observables or LiveData. This makes it possible for the data model and the graphical user interfaces to be up to date and minimizes crossing between the two areas.
ConclusionData binding in Android can be described as a strong feature aimed at optimizing your code and making it easier to read. In general, no matter with activity, view or fragment, data binding can improve important aspects of the UI like response and cleanness. Make use of the data binding in your projects now and see the difference!
|