Android data binding is not working with attributes

前端 未结 2 1095
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 02:49

I\'m trying to use databinding with custom views (a possible usage George Mount showed here).

One can\'t imagine building compound views without <

相关标签:
2条回答
  • 2020-12-09 03:25

    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.

    <layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        >
    
        <data>
            <variable name="data" type="com.example.MyViewModel"/>
        </data>
    
        <merge
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                app: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")
    public static void setGone(View view, boolean isGone) {
        ViewDataBinding binding = DataBindingUtil.findBinding(view);
        //... do what you want with the binding.
    }
    
    0 讨论(0)
  • 2020-12-09 03:33

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

    Ex:

    incl_button.xml

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

    fragment_example.xml

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

    ExampleFragment.kt

    binding.layoutBtn.btn.setOnClickListener{
       //...
    }
    
    0 讨论(0)
提交回复
热议问题