我发现了新的 android 架构组件,我想通过一个小的测试应用程序来测试这对 ViewModel / LiveData。后者有两个片段(在 a 中ViewPager),第一个创建/更新卡片列表(通过 an EditText),第二个显示所有卡片。
我的视图模型:
public class CardsScanListViewModel extends AndroidViewModel {
private MutableLiveData> cardsLiveData = new MutableLiveData();
private HashMap cardsMap = new HashMap();
public CardsScanListViewModel(@NonNull Application application) {
super(application);
}
public MutableLiveData> getCardsLiveData() {
return this.cardsLiveData;
}
public void saveOrUpdateCard(String id) {
if(!cardsMap.containsKey(id)) {
cardsMap.put(id, new Card(id, new AtomicInteger(0)));
}
cardsMap.get(id).getCount().incrementAndGet();
this.cardsLiveData.postValue(cardsMap);
}
}
Run Code Online (Sandbox Code Playgroud)
我的第二个片段:
public class CardsListFragment extends Fragment {
CardsAdapter cardsAdapter;
RecyclerView recyclerCardsList;
public CardsListFragment() {}
@Override
public void …Run Code Online (Sandbox Code Playgroud) android android-fragments rx-android android-livedata android-viewmodel
我使用 a 的绑定ListAdapter和 a 的定义DiffUtil.ItemCallback。删除项目(至少 2 个)时,我有一个IndexOutOfBoundsException. 列表的更新有效(删除后元素的数量确实是N-1),但项目的位置不起作用,保留的是调用。因此,在调用时会抛出异常getItem(position)(在 中onBindViewHolder)。getItemCount()注意:之前的日志getItem(position)显示列表包含 N-1 个元素。我创建了一个小型存储库:https://github.com/jeremy-giles/DiffListAdapterTest(与我的项目具有相同的配置),它重现了问题。
项目适配器类
class ItemAdapter(
var listener: ListAdapterListener) : DataBindingAdapter<Item>(DiffCallback()) {
class DiffCallback : DiffUtil.ItemCallback<Item>() {
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem
}
}
override fun getItemViewType(position: Int) = R.layout.recycler_item
override fun onBindViewHolder(holder: DataBindingViewHolder<Item>, position: Int) …Run Code Online (Sandbox Code Playgroud) android android-recyclerview android-diffutils android-listadapter