我是 Android 新手,我正在尝试使用新架构组件实现条码阅读器场景。
每次读取条码时,我想更新 ViewModel 中的列表,如果列表中不存在条码或增加数量,则添加一个新元素。
以下解决方案有效,但在适配器上调用“notifyDataSetChanged”以更新 UI 并不能让我满意。这是因为 ViewModel 列表和适配器内部列表包含对相同对象的引用,因此 DiffUtil 不会捕获任何更改。
有没有更好的方法来更新 UI?除了适配器之外,我还应该考虑处理架构组件的任何改进吗?
视图模型
public class ScannerViewModel extends ViewModel {
private MutableLiveData<List<ProductScan>> scanListLD;
public ScannerViewModel() {
scanListLD = new MutableLiveData<>();
scanListLD.setValue(new ArrayList<ProductScan>());
}
public LiveData<List<ProductScan>> getScanList() {
return scanListLD;
}
public void addBarcode(String barcode) {
List<ProductScan> list = scanListLD.getValue();
ProductScan scan = null;
for (ProductScan item : list) {
if (item.barcode.equals(barcode)) {
scan = item;
break;
}
}
if (scan == null) {
scan = new ProductScan();
scan.barcode …Run Code Online (Sandbox Code Playgroud)