Enable arithmetic operations in your layout xmls
There have been so many instances while creating views using xmls, I’ve wished I could perform arithmetic operations of dimensions. Thanks to DataBinding you can do this now. In this blog I will explain
- How to enable databinding in your android project.
- Enable data binding in your layout file.
- Writing binding adapters.
To enable data binding feature in your android project add the following lines to your build.gradle
dataBinding {
enabled = true
}
Next to make your layout file work with data binding libraries. Surround your layout file with <layout> tag as shown in the below code snippet
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- UI layout's root element -->
<RelativeLayout
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recylerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/dimen1 + @dimen/dimen2"
/></RelativeLayout>
</layout>
Next step is to write BindingAdapters. Below is one such example.
@BindingAdapter("android:layout_marginBottom")
public static void setMarginBottom(View view, float bottomMargin) {
ViewGroup.MarginLayoutParams layoutParams = ViewGroup.MarginLayoutParams) view.getLayoutParams();
layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin,
layoutParams.rightMargin,(int) bottomMargin);
view.setLayoutParams(layoutParams);
}
You can have your BindingAdapters in your class where you inflate your views or you can create a separate class where you have all your BindingAdapters in one place. The method name can be anything you want but the parameters have to be:
public static void yourMethodName(View view, float bottomMargin)
With the above steps you make it possible to have expressions in your layout xml files. Databinding is a powerful library. In this blog I have given one area in which you can apply data binding. For more information regarding databinding refer to android developers guide.
If you found this blog useful please leave a like.