Rafael Toledo Rafael Toledo - 5 months ago 229
Android Question

Disable Swipe for position in RecyclerView using ItemTouchHelper.SimpleCallback

I am using recyclerview 22.2.0 and the helper class ItemTouchHelper.SimpleCallback to enable swipe-to-dismiss option to my list. But as I have a type of header on it, I need to disable the swipe behavior for the first position of the adapter. As RecyclerView.Adapter doesn't have a isEnabled() method, I tried to disable the view interaction through the methods isEnabled() and isFocusable() in the ViewHolder creation itself, but had no success. I tried to adjust the swipe threshold to a full value, like 0f ot 1f in the SimpleCallback's method getSwipeThreshold(), but no success too.

Some fragments of my code to help you to help me.

My Activity:

@Override
protected void onCreate(Bundle bundle) {
//... initialization
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
return false;
}

@Override
public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
if (viewHolder instanceof CartAdapter.MyViewHolder) return 1f;
return super.getSwipeThreshold(viewHolder);
}

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

}
};

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}


And I have a common adapter with two view types. In the ViewHolder that I want to disable swiping, I did:

public static class MyViewHolder extends RecyclerView.ViewHolder {
public ViewGroup mContainer;

public MyViewHolder(View v) {
super(v);
v.setFocusable(false);
v.setEnabled(false);
mContainer = (ViewGroup) v.findViewById(R.id.container);
}
}

Answer

After playing a bit, I managed that SimpleCallback has a method called getSwipeDirs(). As I have a specific ViewHolder for the not swipable position, I can make use of instanceof to avoid the swipe. If that's not your case, you can perform this control using the position of ViewHolder in the Adapter.

@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    if (viewHolder instanceof CartAdapter.MyViewHolder) return 0;
    return super.getSwipeDirs(recyclerView, viewHolder);
}