Cannot use Databinding in nested view

154 Views Asked by At

I get the following exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.widget.AppCompatTextView.setTag(java.lang.Object)' on a null object reference

When trying to use databinding on nested view inside my own custom view. My custom extends ConstraintLayout and takes child elements but when trying to use this with databinding in my fragment xml the databinding does not seem to work for the nested views. this is a code example from my fragment. Yes this code is wrapped in a "layout" tag.

<LinearLayout>
    <CustomView
        android:id="@+id/customView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="@{viewModel.showView ? View.VISIBLE : View.GONE}"> <-- works

        <AppCompatTextView
            android:id="@+id/nestedView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{viewModel.changableValue}"/> <-- does not work

    </CustomView>
</LinearLayout>

My CustomView

class CustomView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) {

var binding: CustomViewBinding = DataBindingUtil.inflate(
    LayoutInflater.from(context),
    R.layout.custom_view,
    this,
    true
)

override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams?) {
    if (child.id == R.id.static_view_container) {
        super.addView(child, index, params)
    } else {
        binding.nestedViewContainer.addView(child, index, params)
    }
}

}

and it's layout looks like this

<merge
    android:id="@+id/custom_view_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/static_view_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        ...

    </androidx.constraintlayout.widget.ConstraintLayout>


    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/nested_view_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</merge>

What do i need to do to make binding work in my nested views?

0

There are 0 best solutions below