Skip to content Skip to sidebar Skip to footer

Android Data Binding Is Not Working With Attributes

I'm trying to use databinding with custom views (a possible usage George Mount showed here). One can't imagine building compound views without tag. However, in this s

Solution 1:

There is no merge object after inflation, so there is nothing to assign values to with a merge tag. I can't think of any binding tag that will work on merge.

You can assign the tag to the root element and use the BindingAdapter to do what you want.

<layoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"
    ><data><variablename="data"type="com.example.MyViewModel"/></data><mergeandroid:layout_width="wrap_content"android:layout_height="wrap_content"><ImageViewapp:isGone="@{!data.isViewVisible}"android:id="@+id/image_image"android:layout_width="60dp"android:layout_height="60dp"app:imageUrl="@{data.imagePhotoUrl}"/><!-- tons of other views--></merge></layout>

If you want to do something with the Binding class itself, you can use the DataBindingUtil to find the object from the View.

@BindingAdapter("isGone")publicstaticvoidsetGone(View view, boolean isGone) {
    ViewDataBindingbinding= DataBindingUtil.findBinding(view);
    //... do what you want with the binding.
}

Solution 2:

Actually you can use <merge> tag inside <include> and do data binding.

Ex:

incl_button.xml

<layout><mergexmlns:android="http://schemas.android.com/apk/res/android"><Buttonandroid:id="btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Click"
         /></merge></layout>

fragment_example.xml

<layoutxmlns:android="http://schemas.android.com/apk/res/android"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><includelayout="@layout/incl_button"android:id="@+id/layout_btn" /></LinearLayout></layout>

ExampleFragment.kt

binding.layoutBtn.btn.setOnClickListener{
   //...
}

Post a Comment for "Android Data Binding Is Not Working With Attributes"