具有BindingAdapter的MutableLiveData无法更新视图的可见性 [英] MutableLiveData with BindingAdapter not updating visibility of view
问题描述
即使我多次更新LiveData,我的BindingAdapter也只能运行一次.
My BindingAdapter only runs once even though I update my LiveData multiple times.
public class ButtonViewBindingAdapter
{
@BindingAdapter("hideIfZero")
public static void setHideIfZero(View view, MutableLiveData<Integer> currentPosition)
{
view.setVisibility(currentPosition.getValue() == 0 ? View.GONE : View.VISIBLE);
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.package.PermissionsViewModel"/>
<variable
name="clickHandler"
type="com.package.PermissionsActivity.ClickHandler"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:background="@null"
android:onClick="@{() -> clickHandler.nextSlide()}"
android:text="@string/intro_next"
android:textColor="@android:color/white"
/>
<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:background="@null"
android:onClick="@{() -> clickHandler.previousSlide()}"
android:text="@string/intro_back"
android:textColor="@android:color/white"
app:hideIfZero="@{viewModel.currentSlidePosition}"/>
</RelativeLayout>
</layout>
public class PermissionsViewModel extends ViewModel
{
private MutableLiveData<Integer> currentSlidePosition = new MutableLiveData<>();
public PermissionsViewModel()
{
currentSlidePosition.setValue(0);
}
public void setCurrentSlidePosition(final int position)
{
currentSlidePosition.setValue(position);
}
public MutableLiveData<Integer> getCurrentSlidePosition()
{
return currentSlidePosition;
}
}
当我更新视图模型中的值时,可见性仍然不变. BindingAdapter不会运行多次.我在这里想念什么?我希望它在位置为0时隐藏,否则应该显示.
When I update the value in my viewmodel the visibility does still not change. The BindingAdapter does not run more than once. What am I missing here? I want it to hide when the position is 0 otherwise it should show.
推荐答案
如果您未能在绑定对象上调用setLifecycleOwner()
,则数据绑定仍然有效,但是却无法获取任何更新. IIRC,您在绑定时获得的初始值保存在LiveData
中,但此后什么都没有.
If you fail to call setLifecycleOwner()
on the binding object, data binding still works, but quietly fails to get any updates. IIRC, you get the initial value held in the LiveData
at the time of binding, but nothing after that.
我刚刚提交了功能请求,以获取数据绑定,以便在您无法提交数据时更加明显地抱怨呼叫setLifecycleOwner()
.
I just filed a feature request to get data binding to complain more visibly if you fail to call setLifecycleOwner()
.
这篇关于具有BindingAdapter的MutableLiveData无法更新视图的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!