4

我曾经ItemTouchHelperrecyclerview. 它工作正常。但它只适用于长按。我需要这样做onTouch

ItemTouchHelper.Callback itemTouchHelperCallback = new ItemTouchHelper.Callback() {
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        Collections.swap(strings, viewHolder.getAdapterPosition(), target.getAdapterPosition());
        adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

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

   //defines the enabled move directions in each state (idle, swiping, dragging).
     @Override
     public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
         return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
             ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
         }
    };

这是我使用的代码。请帮我!!!

4

2 回答 2

11
  1. 覆盖ItemTouchHelper'sisLongPressDragEnabled并返回 false

    https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.Callback#isLongPressDragEnabled()

    override fun isLongPressDragEnabled(): Boolean = false

  2. 向 ViewHolder 的实现添加回调并使用它

    buttonToDrag.setOnTouchListener { v, event ->
        listener.onTouch(this, event)
        false
    }
    
  3. 在活动或片段中,使用startDrag

    private lateinit var itemTouchHelper: ItemTouchHelper
    
    override fun onTouch(viewHolder: RecyclerView.ViewHolder, event: MotionEvent) {
        if (event.actionMasked == MotionEvent.ACTION_DOWN) {
            itemTouchHelper.startDrag(viewHolder)
        }
    }
    

我在https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper#startdrag的文档中找到了实现

我亲自尝试过,它就像一个魅力。

于 2019-01-11T04:56:33.680 回答
2

您可以在 onBindViewHolder 中使用以下代码通过触摸开始拖动

holder.layout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent event) {

        ClipData data = ClipData.newPlainText("", "");
        View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
        view.startDrag(data, shadowBuilder, view, 0);
        view.setVisibility(View.INVISIBLE);

        return false;
    }
}); 

布局意味着您的项目布局。在您可以将 DragListener 用于所有其他事件之后,例如

DragEvent.ACTION_DRAG_STARTED
DragEvent.ACTION_DRAG_ENTERED
DragEvent.ACTION_DRAG_EXITED
DragEvent.ACTION_DROP
DragEvent.ACTION_DRAG_ENDED
于 2019-01-11T05:20:53.530 回答