In my recent article Gmail like Inbox we have successfully cloned the gmail’s inbox using a RecyclerView with some cool animations. But one thing missing in that is adding swipe to delete and undo functionalities as gmail does.

In this article we are going to add swipe to delete and undo options in a recycler view. Instead of continuing that article, we are going to start a fresh project to make it simpler to understand.

1. How RecyclerView Swipe works? ItemTouchHelper

With the help of ItemTouchHelper class you can add swipe to dismiss, drag & drop support to RecyclerView. Swiping the row will remove the row from the RecyclerView, but it won’t refresh the data. You can see an empty row displayed on swiping the row. You have to take care of refreshing the list by removing the item from the adapter dataset.

ItemTouchHelper.SimpleCallback provides certain callback methods like onMove(), onChildDraw(), onSwiped() when the row is swiped. Showing the background view, removing the item from adapter can be done using these callback methods.

Below is the code snipped of ItemTouchHelper and attaching it to recycler view. This code has to be bit modified in order to make the swipe and undo works. We’ll see how to do that shortly.

RecyclerView recyclerView = findViewById(;

ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        return false;

    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        // Row is swiped from recycler view
        // remove it from adapter

        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            // view the background view
// attaching the touch helper to recycler view
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);

1.1 Defining the Swipe Directions

The swipe directions can be decided while creating the SimpleCallback(). In this article we just used Left -> Right direction. If you want other directions, you can combine with | operator. We can define LEFT, RIGHT, UP and DOWN directions.

new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT)

1.2 Designing The Layout

Planning the layout is very important while adding background view of the row. Lot of people are providing the background by drawing the view on a Canvas in onChildDraw() method. This will be a tedious process drawing it on a canvas if the background view complex. Design the same in an xml layout is much easier. So I have placed both the foreground and background views in a simple layout using FrameLayout keeping the foreground layout on top.

The foreground view will be always visible in the recycler view, and when swipe is performed the background will be visible staying in a static position.

Below image will give you an idea how the foreground and background views are placed in a frame.

2. Example JSON – Restaurant Menu

I have created an example JSON that contains restaurant menu with proper names and images. We are going to consume this json to display the food items in our RecyclerView list.

3. Creating New Project

Now that we have the required knowledge of ItemTouchHelper, let’s start a new project and see how to get the desired output we are looking for.

Note: This project is developed using Android Studio 3.0 Beta. In order to get this article working, get the latest the version of Android Studio here.

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Open build.gradle located under app folder and add RecyclerView, Glide and Volley dependencies.

dependencies {
    implementation ''
    // glide image library
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    // volley http library
    implementation ''
    implementation ''

3. Add the below resources to your strings.xml, dimens.xml and colors.xml respectively.

    <string name="app_name">Recycler Swipe</string>
    <string name="action_settings">Settings</string>
    <string name="my_cart">My Cart</string>
    <string name="delete">DELETE</string>
    <dimen name="activity_padding_horizontal">16dp</dimen>
    <dimen name="padd_10">10dp</dimen>
    <dimen name="ic_delete">30dp</dimen>
    <dimen name="thumbnail">90dp</dimen>
<?xml version="1.0" encoding="utf-8"?>
    <color name="colorPrimary">#111</color>
    <color name="colorPrimaryDark">#FFF</color>
    <color name="colorAccent">#ea3732</color>
    <color name="bg_row_background">#fa315b</color>
    <color name="item_name">#535353</color>
    <color name="description">#a9a9a9</color>

4. Open styles.xml add the below styles to apply Lighter theme to your app. This make the text to darker as we have white background to toolbar.


    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />


5. Create a class named and extend it from Application. This is a singleton class used to initiate the volley library.

import android.text.TextUtils;


public class MyApplication extends Application {

    public static final String TAG = MyApplication.class

    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;

    public void onCreate() {
        mInstance = this;

    public static synchronized MyApplication getInstance() {
        return mInstance;

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        return mRequestQueue;

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

    public <T> void addToRequestQueue(Request<T> req) {

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {

6. Open AndroidManifest.xml and add MyApplication class to <application> node. Also add the INTERNET permission as we gonna make http calls.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <uses-permission android:name="android.permission.INTERNET" />

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


Now we have all the resources ready. Let’s start adding the RecyclerView and rendering the data by parsing the json.

7. Open layout file your and add the RecyclerView. For my activity I have two layout files, activity_main.xml and content_main.xml

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""


            app:popupTheme="@style/AppTheme.PopupOverlay" />


    <include layout="@layout/content_main" />

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""

        android:scrollbars="vertical" />

8. Create a class named Item.class and add the below. This POJO class contains menu item name, price, description and url of thumbnail image.

 * Created by ravi on 26/09/17.

public class Item {
    int id;
    String name;
    String description;
    double price;
    String thumbnail;

    public Item() {

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getDescription() {
        return description;

    public void setDescription(String description) {
        this.description = description;

    public double getPrice() {
        return price;

    public void setPrice(double price) {
        this.price = price;

    public String getThumbnail() {
        return thumbnail;

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;

9. Create an xml layout named cart_list_item.xml under res ⇒ layout folder. This layout file renders each row in recycler view using the adapter class. Here we are adding an ImageView for thumbnail and few TextViews to display the menu item name, description and price.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android=""


            android:src="@drawable/ic_delete_white_24dp" />

            android:textSize="13dp" />



            android:scaleType="centerCrop" />

            android:textSize="17dp" />

            android:textSize="12dp" />

            android:textStyle="bold" />


10. Create a class named This adapter class will be used to inflate the layouts with proper data in recycler view. I am also adding two additional methods to this class removeItem() and restoreItem(), to remove / add rows to recycler view.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

public class CartListAdapter extends RecyclerView.Adapter<CartListAdapter.MyViewHolder> {
    private Context context;
    private List<Item> cartList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name, description, price;
        public ImageView thumbnail;
        public RelativeLayout viewBackground, viewForeground;

        public MyViewHolder(View view) {
            name = view.findViewById(;
            description = view.findViewById(;
            price = view.findViewById(;
            thumbnail = view.findViewById(;
            viewBackground = view.findViewById(;
            viewForeground = view.findViewById(;

    public CartListAdapter(Context context, List<Item> cartList) {
        this.context = context;
        this.cartList = cartList;

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cart_list_item, parent, false);

        return new MyViewHolder(itemView);

    public void onBindViewHolder(MyViewHolder holder, final int position) {
        final Item item = cartList.get(position);;
        holder.price.setText("₹" + item.getPrice());


    public int getItemCount() {
        return cartList.size();

    public void removeItem(int position) {
        // notify the item removed by position
        // to perform recycler view delete animations
        // NOTE: don't call notifyDataSetChanged()

    public void restoreItem(Item item, int position) {
        cartList.add(position, item);
        // notify item added by position

11. Now we are at the core part of this article i.e adding swipe functionality to recycler view. To achieve this create a class named and and extend the class from ItemTouchHelper.SimpleCallback and override the necessary methods.

> getDefaultUIUtil() will be used by ItemTouchHelper to detect whenever there is UI change on the view. We use this function to keep the background view in a static position and move the foreground view.

> In onChildDrawOver() the x-position of the foreground view is changed while user is swiping the view.

> RecyclerItemTouchHelperListener interface used to send the callback to implementing activity. Here the listener will be triggered in MainActivity once the swipe is done.

import android.view.View;

 * Created by ravi on 29/09/17.

public class RecyclerItemTouchHelper extends ItemTouchHelper.SimpleCallback {
    private RecyclerItemTouchHelperListener listener;

    public RecyclerItemTouchHelper(int dragDirs, int swipeDirs, RecyclerItemTouchHelperListener listener) {
        super(dragDirs, swipeDirs);
        this.listener = listener;

    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        return true;

    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (viewHolder != null) {
            final View foregroundView = ((CartListAdapter.MyViewHolder) viewHolder).viewForeground;


    public void onChildDrawOver(Canvas c, RecyclerView recyclerView,
                                RecyclerView.ViewHolder viewHolder, float dX, float dY,
                                int actionState, boolean isCurrentlyActive) {
        final View foregroundView = ((CartListAdapter.MyViewHolder) viewHolder).viewForeground;
        getDefaultUIUtil().onDrawOver(c, recyclerView, foregroundView, dX, dY,
                actionState, isCurrentlyActive);

    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        final View foregroundView = ((CartListAdapter.MyViewHolder) viewHolder).viewForeground;

    public void onChildDraw(Canvas c, RecyclerView recyclerView,
                            RecyclerView.ViewHolder viewHolder, float dX, float dY,
                            int actionState, boolean isCurrentlyActive) {
        final View foregroundView = ((CartListAdapter.MyViewHolder) viewHolder).viewForeground;

        getDefaultUIUtil().onDraw(c, recyclerView, foregroundView, dX, dY,
                actionState, isCurrentlyActive);

    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        listener.onSwiped(viewHolder, direction, viewHolder.getAdapterPosition());

    public int convertToAbsoluteDirection(int flags, int layoutDirection) {
        return super.convertToAbsoluteDirection(flags, layoutDirection);

    public interface RecyclerItemTouchHelperListener {
        void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position);

12. Finally open and do the changes as shown below.

> prepareCart() method fetches the json from the url, parses it and add the items to adapter data list

> The instance of RecyclerItemTouchHelper is created and assigned to RecyclerView. Here only LEFT direction is defined.

> onSwiped() method will be called when the swipe is performed. Here the important step of deleting the row item is taken place. mAdapter.removeItem() is called to delete the row from the RecyclerView.

> Once the row is deleted, Snackbar is used to show a message with UNDO option. Up on clicking UNDO, the row is restored back using mAdapter.restoreItem() method.

> deletedItem, deletedIndex variables are used to temporarily store the item deleted and the index until the Snackbar was shown.

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;


import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements RecyclerItemTouchHelper.RecyclerItemTouchHelperListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private List<Item> cartList;
    private CartListAdapter mAdapter;
    private CoordinatorLayout coordinatorLayout;

    // url to fetch menu json
    private static final String URL = "";

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = findViewById(;

        recyclerView = findViewById(;
        coordinatorLayout = findViewById(;
        cartList = new ArrayList<>();
        mAdapter = new CartListAdapter(this, cartList);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        // adding item touch helper
        // only ItemTouchHelper.LEFT added to detect Right to Left swipe
        // if you want both Right -> Left and Left -> Right
        // add pass ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT as param
        ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT, this);
        new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);

        // making http call and fetching menu json

     * method make volley network call and parses json
    private void prepareCart() {
        JsonArrayRequest request = new JsonArrayRequest(URL,
                new Response.Listener<JSONArray>() {
                    public void onResponse(JSONArray response) {
                        if (response == null) {
                            Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();

                        List<Item> items = new Gson().fromJson(response.toString(), new TypeToken<List<Item>>() {

                        // adding items to cart list

                        // refreshing recycler view
                }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                // error in getting json
                Log.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();


     * callback when recycler view is swiped
     * item will be removed on swiped
     * undo option will be provided in snackbar to restore the item
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
        if (viewHolder instanceof CartListAdapter.MyViewHolder) {
            // get the removed item name to display it in snack bar
            String name = cartList.get(viewHolder.getAdapterPosition()).getName();

            // backup of removed item for undo purpose
            final Item deletedItem = cartList.get(viewHolder.getAdapterPosition());
            final int deletedIndex = viewHolder.getAdapterPosition();

            // remove the item from recycler view

            // showing snack bar with Undo option
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, name + " removed from cart!", Snackbar.LENGTH_LONG);
            snackbar.setAction("UNDO", new View.OnClickListener() {
                public void onClick(View view) {

                    // undo is selected, restore the deleted item
                    mAdapter.restoreItem(deletedItem, deletedIndex);

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds cartList to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

Run the project and test the app. Make sure your device is having active internet connection. Here is the screenshot of the final product.

I hope this article explained the swipe functionality very well. If you still have any queries, please post them in the comments section below.

Happy Coding 😀

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk:
  • Oops! I forgot to add that file. Now the article is updated. Please check point #9.

    Thanks for pointing that out.

    • Kid 1412

      Sorry, but apk download file error, you can update again .

  • Sourabh Jain

    Hello Ravi Sir,

    I have one problem I got an error in volley (outofmemory) when i refresh the list from new items if you have any code(help) please notify me. i m very gr8 full to you .. thanks in advance

    • Is the problem occurring in the same article?

      • Sourabh Jain

        yes i got it when i refresh it every 2 second for check new entry

        • Why you are refreshing it so frequently (2 seconds)?

          • Sourabh Jain

            Thanks For Reply

            Its live streaming market price application thats y i need to refresh it please help regarding this topic i m very thanks full to you

          • Okay, but thats not the way to show realtime data. Your app always crashes. Have you considered using Firebase Realtime database?

          • Sourabh Jain

            i m not using any database just use JSON to show Live Market Price

          • Any service that provides live json?

          • Sourabh Jain

            actually a php file convert xml to json and i call this php page every 2 second and show its data on app.

            If you have any idea to this work in different manner please notify me.

          • Making this process scalable is bit difficult. You can use Firebase Realtime Time db or FCM or Socket connections to handle this data in real time.

            If FCM is considered: (not optimal solution)
            When the data is changed, FCM sends notifications to device. Device will make the request to get the latest data.

            If Sockets considered: (Optimal, but scaling matters as maintaining lot of socket connections is difficult)
            The modified data will send in socket tunnel.

            If Firebase Db considered: (Best, works with any number of devices)
            Your php script inserts the modified data into firebase db. The app will automatically refreshes the data when it changed in Firebase db.

            Also you need to consider decreased the frequency. It shouldn’t be 2 secs. You can get started with firebase db here.

          • Sourabh Jain

            Thanks Ravi Sir,

            Tell me one thing more if i use FCM there is no need to call URL every 2 se

  • Priangga Emilsyah
    • What is compileSDK in build.gradle? It has to be 26.

    • Gamis

      You need to cast your view… Put the type… in this case is
      name = (TextView) view.findViewById(

      • Casting was removed in compileSdkVersion 26

  • Jeady Chatrola

    where did you parse json data??
    sir, what is the meaning of below line??

    List items = new Gson().fromJson(response.toString(), new TypeToken<List>() {

    • Yes the json is serialized using Gson library.

  • Eyal Engel

    Thank you for the example.
    What makes the foreground be in front of the red background and hide it? I don’t see anything in the xml or programmatically…

    • It’s the order in which the elements are added to layout (top -> bottom). The bottom one always visible on Top. If you observe cart_list_item.xml, the foreground view is added at the bottom.

      • Eyal Engel

        Thanks. I forgot to explicitly add a background color (white) to the foreground’s RelativeLayout and that solved my problem.

  • Jochen

    Thanks for this example. Is it also possible to swipe only for the width of the trash icon and delete by touching the icon? Hope you can help me.

    • I have tried achieving that functionality but google has removed that user experience recently.

      • Jochen

        That’s bad. But thanks for your answer.

  • Neon Ds
  • Muhammad Alvin Ramadhan

    Hi Ravi, May i request a tutorial about RxJava 2 ?

    • Arthur L Washington

      alert(‘This is an XSS Vulnerability’)

      • Amit Singh

        stupid noob 😀

  • Renan Bolonha

    Hi Ravi, Can u make a tutorial with ANIMATTION ? Like a when you click in a card and the same move to next activity something like that. Thank you. And I would like say to you, that you make a excelent job here. Congratulations.

  • Ravi Lukka

    Hi Ravi, Can we give swipe right to left & left to right in single item? If yes then please share me tutorial or changes.

    • You need to add RIGHT direction in itemTouchHelper ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT

      ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, this);
      new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);

  • Valdemar Colichon
    • Are you using Retrofit library?

      • Valdemar Colichon

        no, solo volley.

        • Valdemar Colichon

          tu mismo codigo como podria trabajarlo para que reciba result.

          • Gamis

            Yo recomiendo retrofit es mucho mas sencillo y mucho mejor que volley.

          • Learning Retrofit is little difficult in the beginning, but later it makes development much easier.

          • Juan Valdemar Colichon Ramirez

            with that same code as would

        • Consider using Retrofit, it will be much easier to parse.

  • Jerry Yu

    Hi Ravi,

    Can you explain why we need to overwrite onChildDrawOver and onSelectedChanged? Seems like only overwriting onChildDraw and clearView is enough for this effect. I commented out these two methods and it still works.


    • If you remove onSelectedChanged(), is click assigned to foreground view working?

      • Jerry Yu

        Yes, in onBindViewHolder I set the viewholder as the listener for foregroundView onClick event.
        public void onBindViewHolder(ContactViewHolder holder, int position) {

        Click events can be properly handled.

  • Jochen

    Thx, looks great. I wanna try this.

  • Shibin Kalliatt

    How can setup this recycler view swipe to delete option in a fragment. I developed as per your instruction in this tutorial and everything seems to be right except when I slide one row from the recycler view, the particular row is not been deleted and the snack bar message is not shown. Is there anything I should do additionally in the case fragment activity.

  • sam

    Everytime you start with a new project but how come I add them to one project? I’m a beginner.

  • Olivier Picault

    Great tutorial ! Works smoothly for me !

  • Azure Li

    HI, Thanks for your nice tutorial, I have a question when I delete the item from database with swipe , I put the callback method in

    public void onLoadFinished(Loader loader, final Cursor newCursor)

    and with this in onSwiped() Method

    int position = viewHolder.getAdapterPosition();
    int rowId = newCursor.getInt(newCursor.getColumnIndex(TimeEntry._ID));
    Uri uri = Uri.withAppendedPath(TimeEntry.CONTENT_URL, String.valueOf(rowId));
    getContext().getContentResolver().delete(uri, null, null);

    It is ok to delete the first swipe, but the next swipe will cause a crash with newCursor closed
    java.lang.IllegalStateException: attempt to re-open an already-closed object:

    can you help me? thanks

  • Ankush Shinde

    hi…. how to display the product list
    I have a textview i want to display the product list in recycler view ..
    when i click the textview that time i want to display the product list..

  • Sait Sami Kocataş

    Neat explanation, thanks

  • Sait Sami Kocataş

    I think background view needs to be used on RecyclerItemTouchHelper rather than foreground view

    • What is the problem?

      • Sait Sami Kocataş

        pinky delete view pops up front immediately if i use foreground view on RecyclerItemTouchHelper methods. I think idea is it should stay behind the original view while user swipes

  • shiva pasunoori

    Great Tutorial ,Sir if you don’t mind can u provide a tutorial on Expandable Recycler View.
    So many members are waiting for your tutorial.

    Thanks in advance

    • I’ll prepare one. Noted it down.

      • shiva pasunoori

        Tq sir,But its very urgent to me.
        Can u make it as soon as possible

      • shiva pasunoori

        Sir,Please prepare a expandable recycler view tutorial

  • Muwaffaq Imam

    Thank you very much

  • hamza mughal

    I am using retrofit but my onSwiped method in MainActivity getting Position 0 and size as 0 as well..
    Help me out please

  • Divyajyoti Kumar

    Thanks a lot for this tutorial 🙂

  • Kevin Moses Kenap

    Hello sir, thx for tutorial. This is very cool! Do you have tutorial similiar like this, but use firebase instead volley ?

  • Kevin Moses Kenap

    Hello sir, this tutorial is really cool! I follow it with some modification. I try using FirebaseRecyclerAdapter to show the data. But, the problem is, layer to delete and layer to show item information show up at the same time before i try to swipe it. Can you help me please? Thx

  • Kevin Moses Kenap

    Can you give click listener in this tutorial? Can explain me how? Thx

  • akhil

    Every thing is good But I want to delete data from my database .How could it be possible.Please suggest

    • For sqlite, I use a method from mySqLiteHelper: db.deleteFavoriteName(name);

  • Vikas Tomar

    Sir what was the need of creating a singleton class and why do we use TAG. Also, why are we tagging the requestqueue

  • sreedwish k jagan

    Hi Ravi, How to solve this problem : background view come along with foreground view when I swipe.

    • Any screenshot?

      • sreedwish k jagan

        I want bgview to stay in it’s position (just like your screenshot and video) until the item removed.

        • What is parent the layout used. Consider using same as in tutorial.

          • Ryan

            I am having the same issue. I’ve tried duplicating the layouts exactly as well as trying others. For some reason the underlying relative layout is dragged with the foreground relative layout.

          • Can you paste your layout code?

          • geeta

            What part of code in the article above is making the background view not to move when you move the foreground view?

        • geeta

          were you able to solve this issue?

    • Ali Zeynali

      I had the same problem but solved ! consider you have to override `onChildDraw` and `onChildDrawOver` both. I was just Overriding `onChildDrawOver`

      • geeta

        It didn’t solve the issue. Could you please share code?

    • Dimitrios Psirogiannis

      For someone with the same problem try to remove call on super in OnchildDraw(), clearView() and onChildDrawOver()

  • mr.av

    If the list fills the entire screen and I delete the first element, then when I press the undo the deleted item is restored but the list itself does not scroll down to see this item.

  • Pablo

    Hello, Ravi,
    how can I implement a drag and drop (onMove) without showing the red background? I’m being able to drag and drop items correctly, however the red background appears when I do it. So, how to do it as if there were only the foreground in the layout?

  • mr.av

    !!! If the list fills the entire screen and I delete the first element, then when I press the undo the deleted item is restored but the list itself does not scroll down to see this item.

  • Bhavik Makwana

    Hi Ravi, Nice tutorial
    I have dialog when i swipe to LEFT,
    Yes then remove item and if No then foreground_view should appear again.

  • Lor’themar Theron

    Hello it gives this error. “Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.example.arlequina.swiperecyclerview.MyApplication.addToRequestQueue(’ on a null object reference”

    • Add MyApplication class to AndroidManifest.xml.

      • Lor’themar Theron

        Ye u r right, thanks. But i can’t see image and description text. I checked all id and views. How could it possible?

  • Kuldeep Kumar

    Hi sir…
    i have used retrofit display data into list view details activity.
    but when i click add to cart button it shows notification couter. but
    data not showing in cartlist activity.
    sir please give any demo using retrofit … online shoping cartlist
    to display data with cart notification alert?
    thank you sir?…

  • Kuldeep Kumar

    in view details activity..

  • Kuldeep Kumar

    how to get data with another My Cart
    activity when i click add to cart button ?

  • Lucas Bergamo

    Not working with itemclicksupport

    longpress and onclick item recyclerview not work anymore, how can i fix ?

  • Srikanth

    The background view is overlapping the foreground when the view loads initially. How do i make the background view not appear in the foreground

    • Any screenshot?

    • Amsavarthan Lv

      Set foreground’s background colour as white.

  • Reda Salih

    HI, how are you, first thanks for this great tutorial. I’m wondering how to do to add edit swipe on left ? please need it urgently

  • Kuldeep Kumar
    hi sir … how to make this layout using recyclerview if i pass the image and price backend…so please. anyone help me.

  • Kuldeep Kumar

    if i pass the data from previous activity ,then cartlist shows like this,then how to remove the items from cartlist …

  • Amit Kumar Verma

    Hi Ravi,
    I want to swipe only half area of item and delete item only on click delete icon.Please help me.

  • Amit Kumar Verma

    Hi Ravi,
    I want to swipe only half area of item and delete item only on click delete icon same as below screen.Please help me.

    • Wasim Shariff

      there is a method in “RecyclerItemTouchHelper” class called “onChildDrawOver-onDrawOver-> divide dx and dy by 2” and “onChildDraw-onDraw-> divide dx and dy by 2

  • Ahmed Suhail

    Hai Ravi,
    The deleted item not re positioning, when I click undo. After dragging left to right or right to left the deleted item is showing.

  • Amsavarthan Lv

    HI bro!, why is the foreground view is overlapping background view during first initialisation of the layout. I followed all the instructions accordingly to the tutorial.

  • Can’t do this. mAdapter.removeItem(viewHolder.getAdapterPosition());

    It says cannot resolve method removeItem.

    • Your Adapter class must have removeItem() method. Check once.

      • Thanks for your quick-reply.
        My Adapter class has that method. I figured out that I cannot call the method from Adapter class directly so my code goes like this:


        Hope this is the right approach…
        Thanks for the awesome tutorial.

        • Okay. But it should be accessible. What is the Class named used while declaring the variable. XXXX mAdapter?

          • Class name is RecyclerView.Adapter.

          • It should be NewAdapter2 mAdapter;

  • Er Kimmi Arora

    While deleting, white screen is showing, But in gmail there is no white screen. There animation is just perfect

  • Hamza Shammout

    Thank you very much for this tutorial.
    my question is that how to add third layout for swiping right.
    What I exactly want is left swipe for deleting and right swipe for editing so it should have different layouts
    again thank you very much

  • Леня Захаров

    Hi, @ravi8x:disqus ! Can you tell me how change code to create it in Fragment instead Activity? I wrote your code from the MainActivity in the Fragment and replaced “.this” by “getActivity()” and other litle changes. But when i load fragment application is crashed. PS i use fragments from your tutorial about bottom toolbar

    • Any error report?

      • Леня Захаров

        Sorry, man, i soluted it by myself, but your reaction so fast. It’s very cool, thank you ;))

  • Khalid ELQMACHE

    Hi Ravi,
    Can you tell me how to remove outline between row ?

  • David Ryan Sabadash

    Had this problem too, Compiler thinks that “this” is referring to the main activity(with no listener implementation) and does not understand the listener portion of the method call. change the MainActivity class to be
    public class MainActivity extends AppCompatActivity implements RecyclerItemTouchHelper.RecyclerItemTouchHelperListener {

    Should get rid of the error.

    now i just need to get the background view to stop staying on top, i’m having a problem where i cannot swipe because the garbage can icon view is overlapping the recycler entry. it still responds to onClick and onLongClick, but doesn’t show any text (name, etc) anymore, or respond to any swiping. i think i did one of the XML documents backwards or something. any suggestions?

  • David Ryan Sabadash

    Hey, first of all, thank you for all the amazing tutorials you are doing.

    I’m having an issue where both the garbage can icon and the correct recycler information(title, etc) are being displayed at the same time, but the onSwipe method is not being called.

    i implemented onTouch and onLongTouch from a previous tutorial, and they both respond correctly, but swiping left does nothing. In debugger mode, no activity or method calls are being recorded.
    Any suggestions?

    • David Ryan Sabadash

      If it helps anyone, the answer to this problem was;
      mAdapter was initialized but not assigned to new CartListAdaper a la:
      mAdapter = new CartListAdapter(this, cartList);

      and yes i did have the XML layout backwards, displaying the garbage can icon (background view) on top of the recycler view foreground.

  • Vitlero

    Hello @ravi8x:disqus ,
    I tried to follow the code and it works, but I am having an issue when swiping it immediately moves the foreground to the back and shows the background on top, then while swiping it does move the “foreground” correctly, but it moves it behind the background. What might be the issue? I even copy pasted your code into my project but had the same results [ I am using 2 card views instead of 2 Relative layout as parent, the cardview does have a relative layout inside him that contains the items].
    Noticed you do “viewBackground = view.findViewById(;” but never use it

  • Andres Sigala

    Works perfectly but i need it to stop mid way out, just to show the background layout, and on that layout have extra options, like select, delete, and save, so the user can decide what to do with the card, is that possible?

  • Ahmed Ayman

    Please i replaced the snackbar with alert Dialog, and want if the user pressed Keep button, the item to return to its previous state, what happens is the background still visible if the user presses keep and have to swipe right to show the item it self, any solutions please ?

  • Provakor Konik

    Brother your blog hlep me a lot. i m very newbie . but successfully do this . can you please help me little bit more…. I don’t want to connect it by JSON … i want to connect it by firebase database… what should i write there …. hopefully u can help me …. by the way Thanks a lot bro… you are genius <3

  • Chandan Kumar

    This tutorial is great, but if you swipe from right to left still card is getting dragged and becomes invisible how to fix the dragging from only one direction. Please help me out in this.

  • Chandan Kumar
    • Have you used both right and left directions?

      • shanti

        can u provide same thing for list view swipe to delete without external library.

  • Vinay LoHariya

    Whats A dependencies for android studio 2.3.3 that
    dependencies can’t accept in my project Plz send me they all

  • Manas Ranjan Sahoo

    can i add my own json url?

    • Yes you can but you need to the model classes according to your JSON structure.

  • Shivakumar Natarajan

    I tried and it is working. I implemented another recyclerview inside the foreground layout and i linked it to the itemtouchhelper inside adapter viewholder . I want to enable swipe if the username matches, which is working fine with parent but it comes to child when i try swipe nothing happens eventhough condition matches. Priority always goes to the Parent. I attached image of getswipedir method.

  • karthick Ramanathan

    hi ravi, i tried this ,it working thank you, but i want to hold the view swipe partially and to delete item when the button is clicked. i tried example like this , here they used rect to create buttons. I like the approach of foreground and background view and not creating rect. Is there any other way to create swipe with buttons in your method

  • Ronaldo Geldres

    Hi Ravi, firstly Thank you for sharing your knowledge, your tutorials are very useful, I have a doubt , I know I can use ItemTouchHelper.RIGHT or ItemTouchHelper.LEFT to know what event I wnat to execute, but I have a problem with the options that are showed to the user.

    it’s the same than yours, I added just the left button, the problem comes here, when you slide right to execute the event, you can see the left button and viceversa and I think it looks bad, so do you know what is the best option to resolve this? In advance I appreciate your help.

    • Hi Ronaldo

      This may be because of Android version. Could you post your screenshot? Even I need to check this app in new versions and fix if there are any bugs.

  • Dhiren

    Thank you very much for this tutorial Ravi.

    but, I have one issue, while swiping(deleting) first 0th position in recycleView,
    I got below error (happened with only first 0th position, rest works fine):


    Process: com.exmple.myapplication, PID: 11139
    java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 0(offset:-1).state:3{8f2dc49 VFED….. .F….ID 0,0-720,1121 #7f0902b9

    to overcome this issues I tried below 2 possibilities:

    inside activity->onSwiped method :

    if (position == 0) {

    inside adapter

    public void removeItem(int position) {
    if (position == 0)

    by applying above cases,
    while swiping(deleting) view_background (delete view) is appeared on its next position, my recycleview item stuck at “view_background” card. (check the screenshot)

    how may resolve it ? please help.

    • Hi

      Instead of applying a patch you can figure out why that is happening. My be you can print the array sizes and debug.

      • Dhiren Khatik

        ok, I’ve removed all patches,
        I’ve checked my array size is 3, it has 0,1,2 positional elements, while deleting 0th position
        I got inconsistency detected error.

        java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 0(offset:-1).state:3{8f2dc49 VFED….. .F….ID 0,0-720,1121 #7f0902b9

        I don’t know what exactly happened ?

        you can see this stackoverflow question, this same as happened with me.
        and by applying their solution an issue occurred which is mentioned in screenshot!

    • EdwardMuturi

      hey,had the same issure, but fixed it with recyclerView.setAdapter(params). Simply updating the recyclerview with your adpater inside swipe in main activity

  • elmehdi

    how add multiple action. add click listner for delete icon

  • elmehdi

    add click listner to viewBackground

  • Your MyApplication class is not added to AndroidManifest.xml application tag.

  • siddharth bisht

    Hello I am encountering a problem… the foreground and background view are overlapping.
    WHen i swipe it the item gets deleted, but initially I see both the background and foreground view in my recylcer view row

    • Same issue here, any solution?

      • Tom Dev

        see above answer 🙂

    • Tom Dev

      For this problem you have also to set a background to the “viewForeground” if not, the view is transparent and the “viewBackground” is always visible.

      For example like this

  • Khalid EL AYOUBI

    Thanks a lots for your posts, they helped me a great deal.
    Your website is one of the best.

  • Parvin Malek

    sir if i m using tablayout with viewpager so how can i implements this swipe functionality??????????

  • Sanjeev Karat

    What if I have to swipe both directions LEFT & RIGHT? The delete icon in background of listitem if set to both the sides LEFT & RIGHT shows on both sides while it swiping away. Any suggestions Ravi?

  • balan paul

    Hello @ravi8x:disqus

    If I want to load the cartlist (in the prepareCard method) from Firebase using addListenerForSingleValueEvent do I need to make a back-end for the request, because the adapter doesn’t always load.

    Thank you in advance!

  • mehmet arslan

    thx for the great code Ravi. Do you think can we use this approach to remove single cardview easily(without being inside of recycleview ) or may there be a simpler way for that? Thanks again

  • shanti

    hi how do u use anchor point where after swipe foreground and background views visible I mean like in yahoo mail we swipe left then swipe is stopped at some anchor point in which both views are visible

  • Mustafa Shaikh

    while doing undo how to store again in database…????

  • pavi purushothaman

    @ravi8x:disqus Hi, A very thanks for this article. I just tried this and its working perfectly fine. But i want to disable the swipe option for specific items in my Recyclerview. I googled and found that this would work. But this doesn’t seem to work for me.

    public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    if (viewHolder == “my Condition”) return 0;
    else return super.getSwipeDirs(recyclerView, viewHolder);

    I even tried the below one, but no luck.

    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    if (viewHolder == “my Condition”) return 0;
    else return makeMovementFlags(0, ItemTouchHelper.START);
    Could you please help me out with this.

  • Trilok Singh Shekhawat

    Hello Ravi sir Its best tutorial of swipe view , i make ui some diffrent when swipe right to left any view then swipe open and another view swipe left to right then open view is close how to do it please help me

  • Nick Nelson

    Hi Ravi, thanks a lot for the tutorial and answering everyone’s question. I got it working perfectly fine, but would like to use the RecyclerItemTouchHelper in multiple activities. What is the best way to achieve this given the fact that we are referencing the CartListAdapter class explicitly in the onChildDraw, clearView, and onChildDrawOver methods? I don’t want to have to duplicate that class just to change the references to the CartListAdapter. Thanks again!

  • Pawan Singh Dhami

    How to customize row swipe, so that we can delete and undo on icons/ buttons click to n background view.

  • Roja

    Hello Sir . I want deleted item will save in one Activity , How is it possible ?
    Tell me sir. Thankyou in Advance

  • Zohaib Malik

    i want to strikeout the text on swipe how can this be implemented using ItemTouchHelper???

  • Shivs

    This is genius.

  • Venky

    add MyApplication in Manifest as android:name=”MyApplication”

  • Rishabh Saxena

    Hi @ravi8x:disqus, Great tutorial, Can I make it like how whatsapp do for reply ?
    Can you guide me for that ? Like how can i pause this half way while swiping ?

  • Mujahid

    Hi Sir Ravi i need your help i want to know how i can click on background delete button please help me i really nedd this.

  • suresh kamble

    This is the tutorial i was looking for thank you sir .

  • suresh kamble

    sir can you tell me how to add items in the cart

  • Mai Văn Mạnh

    Thank you for sharing a nice post. I wonder a situation when I want to show ripple effect when clicking on the item of recycle view. If I use android:background=”?android:attr/selectableItemBackground” then the ripple effect work but the hidden view beind reveal. By setting background white, the hidden view behind is overcast but the ripple effect doesn’t work.

  • eoin

    how do i set a click listener on the icon on the overlayed item?

  • eoin

    `anyone know how to click on the “delete” icon which is initially overlayed if i only do a partial swipe????

    • Kishore Kumar

      Use List view

  • eljara

    Hi , thanks alot

    i have one question , how can i add the swipe to a an activity that extends from Fragment

  • s Abdul wajid

    hello ravi sir,while am running program getting error in MainActivity in this line MyApplication.getInstance().addToRequestQueue(request); and also getting error in this line prepareCart();
    please help me and solve my problem…

  • Imran Uppal

    Hi Ravi,
    This is awesome tutorial but I am facing a problem, background view is visible over foreground view when activity opens. How to handle?

  • Acauã Pitta

    advanced! 8.5/10 because when you already got the code and just need help in layouts and listener the code it can be resumed

  • Saad Usman

    Amazing Post. Thank you Ravi

  • Shivam Oswal

    Do I need to write a separate piece of code for implementing the back arrow on left top. If yes what would it be? I have set another view using setContentView when button is clicked and implemented the code above. Now I try pressing the back arrow on top left where “My Cart” is written, but it doesn’t work. I should be able to restore my original view when that arrow is pressed is all i need.

  • Gary Arden

    Great tutorial. Can you explain exactly what convertToAbsoluteDirection does and how / when it is used or overridden?

  • Philip Afriyie

    Hi, first of all very great tutorial.
    secondly, please how do you do the samething using firebase realtime database.