androidViewModel + recyclerview 在模型更新时滚动跳转(MVVM)

androidViewModel + recyclerview scroll jump on model update (MVVM)

我有一个关于 recyclerview + mvvm 实现的非常具体的问题。

当我 select 在 recyclerview 中使用 ListItem 时,我的视图模型 class 获得了点击,它在 [=10= 上应用了 "isselected" 标志]加上recyclerview(间接)观察到的MutableLiveData class。这会导致 mainactivity 中的观察者更新整个 List<ListItem>,它由 recyclerview 显示。

结果是,每当我 select recyclerview 中的一个项目时,recyclerview 将向上滚动,(大概)因为整个列表已更新,并且它将更新后的列表视为一个全新的列表。

如何在干净的代码中调整此行为,最好是 mvvm 模式。

(可能是记录点击位置的解决方案,如果这个位置存在,新列表立即"scrolled"到这个位置。但我不知道如何实现这个,如果可能的话。)

事实证明这是一个很常见的问题,但我使用 google 的搜索措辞误导了我。

这个 Whosebug 答案解决了我的问题:

Refreshing data in RecyclerView and keeping its scroll position

//add a Parcelable field to save the state
private Parcelable recyclerViewState;

//before updating the adapter with live data
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

//after updating the adapter with live data
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);