android - Android-具有LiveData的DataBinding保留旧值

标签 android mvvm data-binding android-databinding android-livedata

我设置了DataBinding,并使用ViewPager BindingAdapter在屏幕之间切换:
BindingAdapter

@BindingAdapter("app:nextPageListener") fun nextPageListener(viewPager: ViewPager, next: Boolean?) {
  next ?: return
  if (next) viewPager.nextPage()
  else viewPager.previousPage()
} 
View Pager
<ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:nextPageListener="@{viewModel.nextPageListener}"
    />
viewModel.nextPageListener
  private val _nextPageListener = MutableLiveData<Boolean>()
  val nextPageListener: LiveData<Boolean> get() = _nextPageListener

我的问题是,如果我调用_nextPageListener.postValue(true)并转到下一页,并在某个时候离开屏幕,当我返回时,BindingAdapter会自动用true调用,这会使寻呼机转到下一页。因此基本上在接下来的所有时间中,都在第二个屏幕上打开寻呼机。

不知道它是否与生命周期有关,但是否有帮助,这就是我所拥有的
binding.lifecycleOwner = viewLifecycleOwner

任何想法如何在没有一些丑陋的解决方法的情况下解决此问题?

最佳答案

是的。您可以使用Event类。

open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peekContent(): T = content
}

现在,您可以像这样包装LiveData
   private val _nextPageListener = MutableLiveData<Event<Boolean>>()
val nextPageListener: LiveData<Event<Boolean>> get() = _nextPageListener

最后一步。
yourVm.nextPageListener.observe(this, Observer {
            it.getContentIfNotHandled()?.let {
                when (it) {

                  //get Your value here.
                }
            }
        })

关于android - Android-具有LiveData的DataBinding保留旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61384927/

相关文章:

java - 按钮错误viewflipper android

android - 设置即将与操作栏支持库一起溢出

android - 如何在 onBindViewHolder() 中膨胀和循环 View ?

c# - Canvas 上的MVVM WPF图像

c# - 从 ViewModel 强制刷新,没有任何变化

wpf - 在双向绑定(bind)中将 IValueConverter 与当前 DataContext 一起使用

WPF:XAML 中的绑定(bind)列表 - 项目如何知道其在列表中的位置?

android - Gradle 'AppName'项目刷新失败

c# - 防止在数据网格上添加空白行

c# - 如何更正此说明 WPF DependencyProperty 用法的示例?