首页 > 解决方案 > Android如何在不改变视图可见性的情况下调用绑定适配器?

问题描述

我正在使用 bindingAdapter 来设置基于state.

但是 bindingAdapter 仅在视图重新膨胀或可见性更改时才起作用。有没有办法在不重新膨胀或改变可见性的情况下调用绑定?

 @BindingAdapter("bgClickable")
fun bgClickable(layout: ConstraintLayout, state: String) {
    when (state) {
       DISCONNECTED -> {
            val outValue = TypedValue()
            layout.context.theme
                .resolveAttribute(android.R.attr.selectableItemBackground, outValue, true)
            layout.setBackgroundResource(outValue.resourceId)
        }
        else -> {
            layout.background = null
        }
    }
}

看法

.
.
.
 <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/layout_location"
            android:layout_width="wrap_content"
            app:bgClickable="@{viewModel.getCurrentStatus()}"
            android:layout_height="wrap_content"
            android:onClick="@{()->viewModel.redirectToExplorer()}"
            app:layout_constraintBottom_toTopOf="@+id/guideline3"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.25">
<.../>

标签: androidkotlinbinding

解决方案


绑定适配器的一个常见错误是不将 a 添加lifecycleOwner到绑定对象,没有它,对底层实时数据的更改将不会通知绑定对象。所以在片段/活动类中添加以下内容

binding.lifecycleOwner = this

推荐阅读