Data binding is not new anymore. Many apps are currently now using data binding. Even on the web, many frameworks are now using data binding. One such example is use of data binding with Knockout.js
However, the data binding docs is still under development and android data binding is updated parallel to the release of new version of android studio. So we can hope that in upcoming versions of the android studio we will have better support for android data binding.
If you haven’t gone through the android data binding yet, I strongly suggest you to have a look following topics/series:
https://developer.android.com/topic/libraries/data-binding/index.html
https://medium.com/@georgemount007
In this blog, we will see various live example of android data binding setter’s
DIMENSION ARITHMETICS
In the given example, we are adding two dimensions and using it to set the views dimension.
1 2 3 4 5 |
<android.support.v4.widget.NestedScrollView android:id="@+id/order_details_container" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_marginBottom="@{@dimen/button_height_generic + @dimen/spacing_generic}"> |
1 2 3 4 5 |
@BindingAdapter("layout_marginBottom") public static void setLayoutMarginBottom(ViewGroup view, float marginBottom) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); params.bottomMargin = (int) marginBottom; } |
SETTING FONT
We can also take advantage of data binding to set the custom font of the application.
1 2 3 4 5 6 |
<android.support.v7.widget.AppCompatTextView android:id="@+id/label_odoo_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/odoo" app:font="@{&quot;gill_sans_mt.ttf&quot;}"/> |
1 2 3 4 |
@BindingAdapter({"font"}) public static void setFont(TextView textView, String fontName) { textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName)); } |
CREATING UTILITIES FOR CODE REUSABILITY AND CLEAN CODE
We can also create custom bindings to prevent writing extra code and reusing the same binding utility method at design time. In this example, we are setting HTML text to a text view via data binding.
1 |
app:htmlText="@{title}" |
1 2 3 4 5 6 7 8 9 10 11 12 |
@BindingAdapter("htmlText") public static void setHtmlText(TextView textView, String htmlText) { if (htmlText == null) { return; } if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { textView.setText(Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY)); } else { //noinspection deprecation textView.setText(Html.fromHtml(htmlText)); } } |
That’s all it take for “lazy” programming 😀 Stay calm and keep coding!