Recyclerview拖放触摸

时间:2019-01-11 04:26:16

标签: android android-recyclerview itemtouchhelper

我已经使用ItemTouchHelper来实现recyclerview的拖放。工作正常。但它只能在长按时起作用。我需要使用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);
         }
    };

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

2 个答案:

答案 0 :(得分:1)

  1. 覆盖ItemTouchHelper的{​​{1}}并返回false

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

    isLongPressDragEnabled

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

    override fun isLongPressDragEnabled(): Boolean = false
  3. 在活动或片段中,使用buttonToDrag.setOnTouchListener { v, event -> listener.onTouch(this, event) false }

    startDrag

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

我已经亲自尝试过,它的工作原理就像是一种魅力。

答案 1 :(得分:0)

您可以在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