Android:检测ObservableList

时间:2017-06-29 09:38:51

标签: java android android-databinding observablelist

我在我的模型中使用ObservableList进行绑定。从ObservableList中删除项目时,我想知道哪些项目已被删除。所以我使用ObservableList.OnListChangedCallback

删除该项后,它将调用onItemRangeRemoved()。但问题是该项目已从onItemRangeRemoved()中的ObservableList中删除。

catDatas.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<CatData>>()
{
    @Override
    public void onChanged(ObservableList<CatData> sender)
    {
    }
    @Override
    public void onItemRangeChanged(ObservableList<CatData> sender, int positionStart, int itemCount)
    {
    }
    @Override
    public void onItemRangeInserted(ObservableList<CatData> sender, int positionStart, int itemCount)
    {
    }
    @Override
    public void onItemRangeMoved(ObservableList<XROrderItemData> sender, int fromPosition, int toPosition, int itemCount)
    {
    }
    @Override
    public void onItemRangeRemoved(ObservableList<CatData> sender, int positionStart, int itemCount)
    {
        for (int idx = itemCount - 1; idx >= 0; idx--)
        {
            CatData data = sender.get(idx + positionStart);  //this line will throw index out of bounds exception
            ...
            ...
            ...
            uninitData(data);
        }
    }
});

知道如何捕获被删除的项目吗?

...谢谢

1 个答案:

答案 0 :(得分:1)

Google的员工忽略了removeAll()方法,因此它不会通知观察者。要解决此问题,请使用以下自定义类:

class MyObservableArrayList<T>: ObservableArrayList<T>() {

    override fun removeAll(elements: Collection<T>): Boolean {
        var success = false
        elements.forEach { if (super.remove(it)) success = true }
        return success
    }

}