如何解决Android:在 Android Studio 中无需更改 LiveData 即可自动更新视图
(编辑:当我在从 setSavedAnimOnUi()
调用方法 activity
之前添加了延迟,该方法负责在启动时更新 visibility
的 ImageViews
,它是现在工作正常。可能是什么原因?我在下面添加了 activity
代码段。)
我正在使用 LiveData
和自定义 BindingAdapter
来更新某些 ImageViews
的可见性。
问题是:当我最小化应用程序并返回时,ImageView
会自动更新,即使 livedata
没有改变。
为什么会这样?有人可以帮我吗?
这是我的代码片段:
Activity.kt
settingsViewModel.readAnimationFromDataStore.observe(this,{
if (!isAnimPaused) { // stopping update when onResume gets called
Handler().postDelayed({ // This is making things work as expected
settingsViewModel.setSavedAnimOnUi(it)
},1000)
})
ViewModel.kt
private val _stateAnim1 = MutableLiveData<Boolean>()
val stateAnim1: LiveData<Boolean> = _stateAnim1
private val _stateAnim2 = MutableLiveData<Boolean>()
val stateAnim2: LiveData<Boolean> = _stateAnim2
private val _stateAnim3 = MutableLiveData<Boolean>()
val stateAnim3: LiveData<Boolean> = _stateAnim3
private val _stateAnim4 = MutableLiveData<Boolean>()
val stateAnim4: LiveData<Boolean> = _stateAnim4
private val _stateAnim5 = MutableLiveData<Boolean>()
val stateAnim5: LiveData<Boolean> = _stateAnim5
fun setSavedAnimOnUi(anim: Int) {
when (anim) {
1 -> _stateAnim1.value = true
2 -> _stateAnim2.value = true
3 -> _stateAnim3.value = true
4 -> _stateAnim4.value = true
5 -> _stateAnim5.value = true
}
}
BindingAdapter.kt
@BindingAdapter("checkMarkVisibility")
fun checkMarkVisibility(view: ImageView,state: Boolean) {
// this log statement is used for getting the logs i have provided below
Log.d("BINDING_ADAPTER","checkMarkVisibility: called. view=$view,state=$state")
if (state)
view.visibility = View.VISIBLE
else
view.visibility = View.GONE
}
layout.xml
<ImageView
android:id="@+id/check_anim1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:scaleType="centerInside"
app:checkMarkVisibility="@{viewmodel.stateAnim1}" // tied with the BindingAdapter
android:src="@drawable/ic_selected" />
<ImageView
android:id="@+id/check_anim2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:scaleType="centerInside"
app:checkMarkVisibility="@{viewmodel.stateAnim2}" // tied with the BindingAdapter
android:src="@drawable/ic_selected" />
<ImageView
android:id="@+id/check_anim5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:scaleType="centerInside"
app:checkMarkVisibility="@{viewmodel.stateAnim5}" // tied with the BindingAdapter
android:src="@drawable/ic_selected" />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。