为什么notifyItemRemoved工作缓慢?

时间:2015-08-13 09:44:12

标签: android android-recyclerview swipe-gesture

我在RecyclerView中实现了滑动和删除功能。但问题是,当我删除项目时,上一个项目上升,并且在此项目下方我看到相同的项目几秒钟,但删除后只有一个项目可见(上一个)另外我尝试使用adapter.notifyDataSetChanged()但当我刷过这个项目时,我可以在前一个位置看到这个项目几秒钟,并且在不到1秒的项目被删除之后。

所以,例如我有列表

  1. 列出item1
  2. 列出项目2
  3. 滑动并调用notifyItemRemoved()后,我看到这样的列表1秒

    1. 列出项目2
    2. 列出项目2
    3. 最后

      1. 列出项目2
      2. 这里是代码

            ItemTouchHelper swipeToDismissTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
                    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                    // callback for drag-n-drop, false to skip this feature
                    return false;
                }
        
                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                    // callback for swipe to dismiss, removing item from data and adapter
                    int itemPosition = viewHolder.getAdapterPosition();
                    Log.v("Position", Integer.toString(itemPosition));
                    adapter_.removeItem(itemPosition);
                }
            });
            swipeToDismissTouchHelper.attachToRecyclerView(chatsRecyclerView_);
        

        我的适配器中的方法

        public void removeItem(int position){
            Cursor cursor = getCursor();
            if (cursor.getCount() != 0) {
                Log.v("Size", Integer.toString(cursor.getCount()));
                cursor.moveToPosition(position);
                String chatIdOnServer = cursor.getString(cursor.getColumnIndex(MegaFleetDatabaseOpenHelper.ChatsTable.ID_ON_SERVER));
                context_.startService(ChatsInfoUpdateService.createLeaveChatIntent(this.context_, chatIdOnServer));
                ChatsTableHelper.deleteChat(this.context_, chatIdOnServer);
               // this.notifyDataSetChanged();
               this.notifyItemRemoved(position);
            }
        }
        

1 个答案:

答案 0 :(得分:0)

解决方案是在删除项目后调用swapCursor()。在这种情况下一切正常。

 @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            // callback for swipe to dismiss, removing item from data and adapter
            int itemPosition = viewHolder.getAdapterPosition();
            Log.v("Position", Integer.toString(itemPosition));
            adapter_.removeItem(itemPosition);
            adapter_.swapCursor(ChatsTableHelper.getAllChatsInfo(ChatListActivity.this));
        }
    });