使用LiveData设置TextView的可见性 [英] Using LiveData to set visibility of TextView

查看:267
本文介绍了使用LiveData设置TextView的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用LiveData切换TextView的可见性.还有其他几篇关于通过数据绑定设置可见性的文章,但是这些文章使用Observables,而我想利用(较新的)LiveData.尤其要使用LiveData.

I want to toggle the visibility of a TextView using LiveData. There have been a few other posts on setting the visibility with databinding, but these use Observables, whereas I want to leverage the (newer) LiveData. In particular, use a LiveData.

使用本文档和一些SO帖子,我已经了解到,您应该正确对齐可观察对象(LiveData)的getter,以使返回类型与setter对于要设置的View属性所期望的类型相匹配.具体来说:

Using this documentation, and a few SO posts, I have already learned that you should correctly align your getter of your observable (LiveData) so that the return type matches the type expected by the setter for the View attribute you want to set. Specifically:

    View的
  • setVisibility()需要一个int,而我有一个LiveData成员(因此ViewModel中的getter也将返回此类型)
  • 可以使用三元运算符将此布尔值转换为View.VISIBLE和VIEW.GONE.我还应该在我的XML表达式中添加safeUnbox()使其成为原始的布尔值

使用这些见解,我在ViewModel类中定义了:

Using these insights, in my ViewModel class, I have defined:

MutableLiveData<Boolean> textHintVisible;

按下按钮后,我将此值设置为False:

After pressing a button, I set this value to False:

textHintVisible.postValue(false);

(注意,我也尝试过使用setValue())

(note, I also tried with setValue())

然后,在我的布局XML中包括:

Then, in my layout XML, I have included:

<TextView
   android:visibility="@{(safeUnbox(viewModel.textHintVisible) ? View.VISIBLE : View.GONE)}"
/>

但是,我的TextView始终可见.为了调试,我在活动中添加了一个观察者,这确认我的布尔值正确地在true和false之间切换:

But still, my TextView is always visible. To debug, I have added an observer in my activity, and this confirms that my boolean is correctly toggled between true and false:

mHintsViewModel.getTextHintVisible().observe(this, new Observer<Boolean>() {
   @Override
   public void onChanged(@Nullable Boolean newInt) {
        Log.i(TAG,"onChanged: "+newInt);
   }
});

但是我的TextView一直保持可见状态.我究竟做错了什么?为此不可能使用LiveData吗?我应该使用额外的转换器吗?还是我的代码原则上是正确的,但这是Android Studio中的错误吗?非常感谢您的帮助.

But my TextView stays visible all the time. What am I doing wrong? Is it impossible to use LiveData for this? Should I use an additional Converter? Or is my code in principle correct, but is this a bug in Android Studio? Any help is much appreciated.

推荐答案

我要记住的一件事是-您是否设置了绑定以观察liveData?根据文档,您必须设置绑定布局以观察生命周期

One thing I have in mind is - have you set your binding to observe liveData? As per documentation you have to set the binding layout to observe lifecycle binding.setLifecycleOwner(this)

这篇关于使用LiveData设置TextView的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆