3

In Android's data binding documentation, it says that

You can also write adapters for android namespace.

I followed the sample code in that documentation and tried to bind to TextView's android:text setter.

This is the BinderAdapter I wrote:

@BindingAdapter("android:text")
public static void setText(TextView view, CharSequence text) {
    view.setText(text + " - the BinderAdapter works!");
    Log.d("MY_TAG", "the BinderAdapter works!");
}

and this is the layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is dummy text"/>

</RelativeLayout>

When I run the app I expect to see the text "This is dummy text - the BinderAdapter works!", however, the text I see is "This is dummy text". Moreover, looking at the logs I don't see the setText() being called.

I read (here) suggestions for using a namespace other than "android", however, it is important to me that I will not need to pay special attention and place different namespaces throughout my app.

What am I doing wrong?

Community
  • 1
  • 1
dors
  • 5,802
  • 8
  • 45
  • 71
  • First, you did not use a binding expression. The data binding framework only evaluates attributes in which you use a binding expression. Second, there already is a binding adapter for `android:text`, and I am not certain what happens if the data binding framework encounters more than one binding adapter for the same thing. – CommonsWare Feb 21 '17 at 23:58
  • Thanks @CommonsWare. I initially thought that setting dataBinding { enabled = true } in the app's build.gradle file was enough to have my views go through BindingAdapter methods, but I understand now that it is not the case. In addition to the binding expression (for example @{@string/test_string}) it seems I also needed to surround my layout with a '...' tags + use DataBindingUtil.setContentView(...) for it to work. One last thing, what do you mean by "Second, there already is a binding adapter for android:text"? – dors Feb 22 '17 at 07:48
  • "what do you mean by "Second, there already is a binding adapter for android:text"?" -- I mean exactly what it says. You do not have to write one. The data binding framework already has one. Quoting the page that you linked to: "The android attributes have already had BindingAdapters created." – CommonsWare Feb 22 '17 at 12:17
  • If this is true (which seems to be the case) then the documentation on `BindingAdapter` is also wrong https://developer.android.com/reference/android/databinding/BindingAdapter.html =( – tir38 May 15 '17 at 15:58

0 Answers0