RecyclerView - 拖动时物品会被回收

时间:2018-05-22 12:44:11

标签: android android-recyclerview itemtouchhelper

RecyclerViewHORIZONTAL。其中每件商品的宽度几乎等于回收商的总宽度。最多只能看到3个ViewHolders

这里有一些模型可以更好地理解结果的外观。

enter image description here

我想在我的RecyclerView中添加重新定位卡片的功能,因此我创建了ItemTouchHelper.Callback并将其附加到RecyclerView

一旦我在任何卡片上长按,我就可以向左和向右拖动它。当我在屏幕边缘移动它时,RecyclerView会自动开始滚动,然后我的视图消失。

据我所知,我猜它会被回收 - ItemTouchHelper#clearView(RecyclerView, RecyclerView$ViewHolder)被调用,它来自RecyclerView#removeDetachedView(View)

有什么可以绕过这种行为吗?

ItemTouchHelper.Callback drag = new ItemTouchHelper.Callback() {

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.START | ItemTouchHelper.END | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            return makeMovementFlags(dragFlags, ItemTouchHelper.ACTION_STATE_IDLE);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int oldPosition = viewHolder.getAdapterPosition();
            int newPosition = target.getAdapterPosition();
            Log.d(getClass().getSimpleName(), String.format("View moved from %d to %d", oldPosition, newPosition));

            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            // Not applicable
        }
    };

mView.recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
mView.recycler.setAdapter(mAdapter = new SimpleAdapter());

ItemTouchHelper touchHelper = new ItemTouchHelper(drag);
touchHelper.attachToRecyclerView(mView.recycler);

Stack from debugger when View disappears

1 个答案:

答案 0 :(得分:0)

开始拖动时ItemTouchHelper.Callback尝试设置

viewHolder.setIsRecyclable(false)

然后当你结束你的拖动

viewHolder.setIsRecyclable(true)