具有Room数据库的Android:滑动列表元素时,动画会损坏

时间:2018-08-08 11:00:34

标签: android android-recyclerview

我正在使用Room + RecyclerView,如下所述: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/

然后,我用“向左滑动”添加了删除列表元素的方法,如下所示: https://www.androidhive.info/2017/09/android-recyclerview-swipe-delete-undo-using-itemtouchhelper/

它可以工作,但是当我从列表中删除该项目后又从数据库中删除该项目时,将列表向上滚动以填充空白处的动画不再起作用:

(excerpt from ListFragment)
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position)
{
    if (viewHolder instanceof mdcPointListAdapter.mdcPointViewHolder)
    {
        mdcPointListAdapter pointListAdapter = ((mdcPointListAdapter) (recyclerView.getAdapter()));
        List<mdcPoint> mdcPoints = pointListAdapter.getPoints();
        // get the removed item name to display it in snack bar
        String name = mdcPoints.get(viewHolder.getAdapterPosition()).toString();

        // backup of removed item for undo purpose
        final mdcPoint deletedItem = mdcPoints.get(viewHolder.getAdapterPosition());
        final int deletedIndex = viewHolder.getAdapterPosition();

        **// remove the item from recycler view
        pointListAdapter.removeItem(viewHolder.getAdapterPosition());
        // remove the item from database through the ViewModel linked to Room database
        mPointViewModel.delete(deletedItem);**

        // showing snack bar with Undo option
        Snackbar snackbar = Snackbar
                .make(mainLayout, name + " " + getString(R.string.removed_from_list), Snackbar.LENGTH_LONG);
        snackbar.setAction(R.string.undo, view ->
        {
            // undo is selected, restore the deleted item
            pointListAdapter.restoreItem(deletedItem, deletedIndex);
            mPointViewModel.insert(deletedItem);
        });
        snackbar.setActionTextColor(Color.YELLOW);
        snackbar.show();
    }

}

相关部分是

        // remove the item from recycler view
        pointListAdapter.removeItem(viewHolder.getAdapterPosition());
        // remove the item from database through the ViewModel linked to Room database
        mPointViewModel.delete(deletedItem);

我的解释是,由于ListFragment“观察”数据库,因此只要使用 mPointViewModel.delete 删除该项目,它就会请求更新列表,并且刚开始的动画是立即取消。

我还尝试覆盖RecyclerView动画制作器的 onRemoveFinished 并将 mPointViewModel.delete 放在此处,但没有更改。

我发现的唯一解决方法是将 mPointViewModel.delete 产生的线程延迟400毫秒:在这种情况下,动画完成了,但是这种解决方案似乎不是很专业。

还有没有更合适的方法来实现这一目标?

谢谢。

0 个答案:

没有答案