我有以下 DataBinding 设置,但只要“isPrivate”为真,可见性就会保持 View.GONE
布局.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:binding="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.motion.widget.MotionLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutDescription="@xml/scene_1">
...
<ImageView
android:id="@+id/iv_car_private"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:src="@drawable/ic_lock"
binding:visibility="@{viewModel.car.isPrivate}" />
...
</androidx.constraintlayout.motion.widget.MotionLayout>
<data>
<variable
name="viewModel"
type="com.app.MyViewModel" />
</data>
</layout>
活动
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).also { binding ->
binding.lifecycleOwner = this
binding.viewModel = myViewModel
}
绑定适配器
@BindingAdapter("visibility")
fun setVisibility(view: View, isVisible: Boolean) {
Timber.d("+++ isPrivate: $isVisible")
view.visibility = if (isVisible) View.VISIBLE else View.GONE
}
@xml/scene_1没有引用 ImageView- 如果我删除该
binding:visibility行,则视图可见 - BindingAdapter 中的 LogOutput 始终打印正确的真/假值
- 我也尝试
binding.invalidateAll()在活动设置中添加,但没有区别
更新:
- 另一个 RecyclerView (它的项目)使用相同的 BindingAdapter 并且可以工作
- 如果我使用以下 BindingAdapter 伪造 invisibiliy,则正确设置了 imageResource(其余代码相同!)
@BindingAdapter("isPrivate")
fun setIsPrivate(imageView: ImageView, isPrivate: Boolean) {
if (isPrivate) {
imageView.setImageResource(R.drawable.ic_lock)
} else {
imageView.setImageDrawable(null)
}
}