sl133
sl133

Reputation: 1359

Android CardView Drag and Drop ItemTouchHelper

I tried to look all over google and SO but couldn't find a solution to my problem.

Basically, I've got a RecyclerView utilizing CardViews, and I want to allow Drag&Drop on those cardviews. Swiping works fine, but in the ItemTouchHelper, Drag and drop doesn't work. I'm not sure why, I've specified the correct movement directions.

I can swipe left and right for the swipeDirs, but Moving up and down doesn't work for the dragDirs. I'm not sure if its an issue with the emulator itself not recognizing "drags" because if I attach UP and DOWN to the swipeDirs, I can swipe in every direction as a test.

I'm not getting any visuals of Drag and Drop working

ItemTouchHelper.Callback scb = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT){
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target){
        //call back to adapter to swap positions, the Error is not with this line of code (at least not yet)
        return true;
    }

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

    }
};

ItemTouchHelper ith = new ItemTouchHelper(scb);
ith.attachToRecyclerView(recyclerView);

Any help is appreciated, Thanks

Upvotes: 0

Views: 1610

Answers (1)

sl133
sl133

Reputation: 1359

Figured it out, you need to Override onBindViewHolder in your Adapter

@Override
public void onBindViewHolder(Adapter.ViewHolder  holder, int position){
    final Adapter.ViewHolder xholder = holder;
    holder.card.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View view, MotionEvent event){
            if(MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN)
                listener.onStartDrag(xholder);
            return false;
        }
    });
}

And then in your RecyclerList containing the ItemTouchHelper

@Override
public void onStartDrag(ViewHolder holder){
    itemTouchHelper.startDrag(holder);
}

Upvotes: 3

Related Questions