我得到以下异常:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void androidx.appcompat.widget.AppCompatTextView.setTag(java.lang.Object)”
当尝试在我自己的自定义视图中的嵌套视图上使用数据绑定时。我的自定义扩展了 ConstraintLayout 并采用子元素,但是当尝试在我的片段 xml 中将其与数据绑定一起使用时,数据绑定似乎不适用于嵌套视图。这是我的片段中的代码示例。是的,此代码包含在“布局”标签中。
<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>
我的自定义视图
类 CustomView @JvmOverloads 构造函数(上下文:上下文,attrs:AttributeSet?= null,defStyleAttr:Int = 0):ConstraintLayout(上下文,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)
}
}
}
它的布局看起来像这样
<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>
我需要做什么才能在我的嵌套视图中进行绑定?