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(R.id.recycler_view);

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

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

    @Override
        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.

https://api.androidhive.info/json/menu.json

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 'com.android.support:recyclerview-v7:26.1.0'
 
    // glide image library
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    
    // volley http library
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.google.code.gson:gson:2.6.2'
}

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

<resources>
    <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>
</resources>
<resources>
    <dimen name="activity_padding_horizontal">16dp</dimen>
    <dimen name="padd_10">10dp</dimen>
    <dimen name="ic_delete">30dp</dimen>
    <dimen name="thumbnail">90dp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <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>
</resources>

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.

<resources>

    <!-- 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>

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

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

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

</resources>

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

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {

    public static final String TAG = MyApplication.class
            .getSimpleName();

    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.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);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

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="http://schemas.android.com/apk/res/android"
    package="info.androidhive.recyclerviewswipe">

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

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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 MainActivity.java 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"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="info.androidhive.recyclerviewswipe.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/white"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

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

</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="info.androidhive.recyclerviewswipe.MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />
    
</android.support.constraint.ConstraintLayout>

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) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.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="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/view_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bg_row_background">

        <ImageView
            android:id="@+id/delete_icon"
            android:layout_width="@dimen/ic_delete"
            android:layout_height="@dimen/ic_delete"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/padd_10"
            android:src="@drawable/ic_delete_white_24dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/padd_10"
            android:layout_toLeftOf="@id/delete_icon"
            android:text="@string/delete"
            android:textColor="#fff"
            android:textSize="13dp" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/view_foreground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:padding="@dimen/padd_10">

        <ImageView
            android:id="@+id/thumbnail"
            android:layout_width="@dimen/thumbnail"
            android:layout_height="@dimen/thumbnail"
            android:layout_marginRight="@dimen/activity_padding_horizontal"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/thumbnail"
            android:ellipsize="end"
            android:fontFamily="sans-serif-medium"
            android:maxLines="1"
            android:textColor="@color/item_name"
            android:textSize="17dp" />

        <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/name"
            android:layout_marginTop="5dp"
            android:layout_toRightOf="@id/thumbnail"
            android:textColor="@color/description"
            android:textSize="12dp" />

        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_toRightOf="@id/thumbnail"
            android:textColor="@color/colorAccent"
            android:textStyle="bold" />

    </RelativeLayout>
</FrameLayout>

10. Create a class named CartListAdapter.java. 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.support.v7.widget.RecyclerView;
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) {
            super(view);
            name = view.findViewById(R.id.name);
            description = view.findViewById(R.id.description);
            price = view.findViewById(R.id.price);
            thumbnail = view.findViewById(R.id.thumbnail);
            viewBackground = view.findViewById(R.id.view_background);
            viewForeground = view.findViewById(R.id.view_foreground);
        }
    }


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

    @Override
    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);
    }

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

        Glide.with(context)
                .load(item.getThumbnail())
                .into(holder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return cartList.size();
    }

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

    public void restoreItem(Item item, int position) {
        cartList.add(position, item);
        // notify item added by position
        notifyItemInserted(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 RecyclerItemTouchHelper.java 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.graphics.Canvas;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
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;
    }

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

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

            getDefaultUIUtil().onSelected(foregroundView);
        }
    }

    @Override
    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);
    }

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

    @Override
    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);
    }

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

    @Override
    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 MainActivity.java 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.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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 = "https://api.androidhive.info/json/menu.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(getString(R.string.my_cart));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        recyclerView = findViewById(R.id.recycler_view);
        coordinatorLayout = findViewById(R.id.coordinator_layout);
        cartList = new ArrayList<>();
        mAdapter = new CartListAdapter(this, cartList);

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

        // 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
        prepareCart();
    }

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

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

                        // adding items to cart list
                        cartList.clear();
                        cartList.addAll(items);

                        // refreshing recycler view
                        mAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            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();
            }
        });

        MyApplication.getInstance().addToRequestQueue(request);
    }

    /**
     * callback when recycler view is swiped
     * item will be removed on swiped
     * undo option will be provided in snackbar to restore the item
     */
    @Override
    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
            mAdapter.removeItem(viewHolder.getAdapterPosition());

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

                    // undo is selected, restore the deleted item
                    mAdapter.restoreItem(deletedItem, deletedIndex);
                }
            });
            snackbar.setActionTextColor(Color.YELLOW);
            snackbar.show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds cartList to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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: ravi@androidhive.info
  • 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.
            https://www.androidhive.info/2016/10/android-working-with-firebase-realtime-database/

          • 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(R.id.view)

      • 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>() {
    }.getType());

    • 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.
    Thanks

    • 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.

    Thanks,

    • 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) {

        holder.foregroundView.setOnClickListener(holder);
        }
        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();
    newCursor.moveToPosition(position);
    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 https://uploads.disquscdn.com/images/8fee4239c53f555a2db342b2f79271b892d93499befe70180cf23a8661573cd9.jpg

  • 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.

        https://uploads.disquscdn.com/images/d4662ab31e64fc1c079ec9524b4903339e69f2e489207c0a10ef74ac815f9bf6.png

        • 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?

  • 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?
    Thanks!

  • 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(com.android.volley.Request)’ 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

    https://uploads.disquscdn.com/images/f1d39206a5793e229fc996234def29f2562b71ff6c5dc196fb5766df373933b5.png
    hi sir … how to make this layout using recyclerview if i pass the image and price backend…so please. anyone help me.
    thanks..

  • 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.

    https://uploads.disquscdn.com/images/06281a23b9f60e728b9af765313676a4000c93d361902eb982ba4ce2665ee851.png

    • 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.

    https://uploads.disquscdn.com/images/8a7d29166cd5e5f079b0f68e549c287b1aec06dba920739d60952a1b5aa51ad9.png

  • 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:

        ((NewAdapter2)recyclerView.getAdapter()).removeItem(viewHolder.getAdapterPosition());

        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

    @ravi8x:disqus
    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(R.id.view_background);” 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

    https://uploads.disquscdn.com/images/da65b4aff67b73b2ed56ed47d63be59cc8b2510463337777aecbb4dbc1b15d11.png

  • 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.
    Thanks.

  • 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
    dependencies…

  • 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. https://uploads.disquscdn.com/images/d37131778f5c21244ccc5d2cddf7d763fc1e2cacf4b33da22c88c34eb4cda085.png

  • 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 https://codeburst.io/android-swipe-menu-with-recyclerview-8f28a235ff28 , 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):

    FATAL EXCEPTION: main

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

    to overcome this issues I tried below 2 possibilities:

    (1)
    inside activity->onSwiped method :

    if (position == 0) {
    binding.recyclerView.getRecycledViewPool().clear();
    adapter.notifyDataSetChanged();
    }
    adapter.removeItem(position);

    (2)
    inside adapter

    public void removeItem(int position) {
    canvassList.remove(position);
    if (position == 0)
    notifyDataSetChanged();
    else
    notifyItemRemoved(position);

    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.

    https://uploads.disquscdn.com/images/f79c124305a48b606e1129ddd13f0cb34edfc08a1ebd7953dab014b96cf68a47.png

    • 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.
        i.e.,

        java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 0(offset:-1).state:3 android.support.v7.widget.RecyclerView{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.
        https://stackoverflow.com/questions/30220771/recyclerview-inconsistency-detected-invalid-item-position
        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

    Hello,
    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.

    @Override
    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.

    @Override
    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.
    TIA.

  • 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