How to use item touch helper with heterogeneous view types?

BVB09 :

I am following this tutorial Item touch helper example (well actually just the item touch helper part and that too because I want the red background with the delete icon seen when swiping). But I have two different view types in my recyclerview. How would I go about implementing it? I am stuck on this line

final View foregroundView = ((CartListAdapter.MyViewHolder) viewHolder).viewForeground;

in the RecyclerItemTouchHelper.java on the onChildDraw method

Ben P. :

All ViewHolder instances have a method getItemViewType() which will return the same value your adapter originally returned from its own getItemViewType() method when the ViewHolder was created. You can use the value here to choose which of your own ViewHolder subclasses to cast to:

public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
    int viewType = viewHolder.getItemViewType();

    if (viewType == MY_FIRST_TYPE) {
        ((MyFirstSubclass) viewHolder).foo();
        // ...
    } else if (viewType == MY_SECOND_TYPE) {
        ((MySecondSubclass) viewHolder).bar();
        // ...
    }

    // ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134880&siteId=1