Android Listview Swipe To Delete Tutorial With Example is covered in this post.
You will learn how to make a listview swipe to show delete button.
We will make a listview in which listview row item will be deleted when the user swipes left or right.
At the end of this example, you will learn to make a listview feature of swipe to delete like in gmail app.
This swipe to remove listview item feature simplifies the deleting process for the user.
First checkout the output video, then we will develop the example step by step.
Step 1. Make a new project.
Create a new project in android studio with empty activity.
Step 2. Adding dimens file
Create a new xml file named dimens.xml under res -> values folder
Add following code in it
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="list_item_padding_sides">16dp</dimen> <dimen name="list_item_height">80dp</dimen> </resources>
Step 3. Updating colors.xml
Update colors.xml file with below
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="gray_background">#757575</color> <color name="yellow">#FFBB33</color> </resources>
Step 4. Create listview row layout
Make a new layout resource file and give it a name list_item.xml
Add below source code in it
<?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:id="@+id/lyt_container" android:background="@color/gray_background"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:background="@android:color/white"> <TextView android:id="@+id/tv" android:layout_width="0dp" android:layout_height="wrap_content" android:height="@dimen/list_item_height" android:background="@android:color/white" android:gravity="center_vertical" android:paddingLeft="@dimen/list_item_padding_sides" android:paddingRight="@dimen/list_item_padding_sides" android:layout_weight="4" /> <ImageView android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/image" android:src="@mipmap/ic_launcher_round" android:layout_weight="2" android:paddingTop="10dp" android:paddingBottom="10dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:visibility="gone" android:weightSum="3" android:height="@dimen/list_item_height" android:paddingLeft="@dimen/list_item_padding_sides" android:paddingRight="@dimen/list_item_padding_sides"> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/txt_delete" android:gravity="center_vertical" android:text="Deleted" android:clickable="false" android:layout_weight="2" android:hapticFeedbackEnabled="true" android:textColor="@android:color/white"/> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:gravity="center" android:id="@+id/txt_undo" android:text="Undo" android:clickable="false" android:layout_weight="1" android:textColor="@color/yellow"/> </LinearLayout> </FrameLayout>
This layout file represents the every single row item of the listview.
In this file, both the layouts are covered :
- A layout which is shown before the swipe action
- A layout which is shown after user swipes the row (undo and delete button)
Step 5. Add Library to build.gradle(Module: app)
Add below line into build.gradle(Module: app) file
compile 'com.hudomju:swipe-to-dismiss-undo:1.0'
We have used external library in this example.
The classes of this library will simplify our work and will save our time.
Visit library on github here.
Step 6. Adding Images
download this images and add to drawable folder
Now put these images in the drawable folder.
You can learn how to add items to the drawable folder here in step 2. (No need to create xml file in drawable, just copy and paste images in drawable).
Step 7. Making Model
Create a new java class named Model.java and add below code
public class Model { private String name; public int getImage_drawable() { return image_drawable; } public void setImage_drawable(int image_drawable) { this.image_drawable = image_drawable; } private int image_drawable; public String getName() { return name; } public void setName(String name) { this.name = name; } }
Step 8. Preparing Custom Adapter
Make a new java class with name CustomAdapter.java
Add following into it
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; /** * Created by Parsania Hardik on 03-Jan-17. */ public class CustomAdapter extends BaseAdapter { private Context context; private ArrayList<Model> ModelArrayList; public CustomAdapter(Context context, ArrayList<Model> ModelArrayList) { this.context = context; this.ModelArrayList = ModelArrayList; } public void remove(int position) { ModelArrayList.remove(position); notifyDataSetChanged(); } @Override public int getViewTypeCount() { return getCount(); } @Override public int getItemViewType(int position) { return position; } @Override public int getCount() { return ModelArrayList.size(); } @Override public Object getItem(int position) { return ModelArrayList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_item, null, true); holder.tvname = (TextView) convertView.findViewById(R.id.tv); holder.iv = (ImageView) convertView.findViewById(R.id.image); convertView.setTag(holder); }else { // the getTag returns the viewHolder object set as a tag to the view holder = (ViewHolder)convertView.getTag(); } holder.tvname.setText(ModelArrayList.get(position).getName()); holder.iv.setImageResource(ModelArrayList.get(position).getImage_drawable()); return convertView; } private class ViewHolder { protected TextView tvname; private ImageView iv; } }
This adapter class contains remove() method. This method will get position as a parameter. It is the same position (a number of row item) which is swiped by the user.
remove() method will delete the row which it has got as a parameter.
Step 9. Updating Main Activity
Update activity_main.xml as below
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" tools:context=".MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview"/> </LinearLayout>
Update MainActivity.java file as below
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.hudomju.swipe.SwipeToDismissTouchListener; import com.hudomju.swipe.adapter.ListViewAdapter; import java.util.ArrayList; import static android.widget.Toast.LENGTH_SHORT; public class MainActivity extends AppCompatActivity { private ListView lv; private CustomAdapter customAdapter; private ArrayList<Model> modelArrayList; private int[] myImageList = new int[]{R.drawable.benz, R.drawable.bike, R.drawable.car,R.drawable.carrera ,R.drawable.ferrari,R.drawable.harly, R.drawable.lamborghini,R.drawable.silver}; private String[] myImageNameList = new String[]{"Benz", "Bike", "Car","Carrera" ,"Ferrari","Harly", "Lamborghini","Silver"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.listview); modelArrayList = populateList(); customAdapter = new CustomAdapter(this,modelArrayList); lv.setAdapter(customAdapter); final SwipeToDismissTouchListener<ListViewAdapter> touchListener = new SwipeToDismissTouchListener<>( new ListViewAdapter(lv), new SwipeToDismissTouchListener.DismissCallbacks<ListViewAdapter>() { @Override public boolean canDismiss(int position) { return true; } @Override public void onDismiss(ListViewAdapter view, int position) { customAdapter.remove(position); } }); lv.setOnTouchListener(touchListener); lv.setOnScrollListener((AbsListView.OnScrollListener) touchListener.makeScrollListener()); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (touchListener.existPendingDismisses()) { touchListener.undoPendingDismiss(); } else { Toast.makeText(MainActivity.this, "Position " + position, LENGTH_SHORT).show(); } } }); } private ArrayList<Model> populateList(){ ArrayList<Model> list = new ArrayList<>(); for(int i = 0; i < 8; i++){ Model model = new Model(); model.setName(myImageNameList[i]); model.setImage_drawable(myImageList[i]); list.add(model); } return list; } }
Understanding the main logic
Look closely at following snippet from Main Activity
final SwipeToDismissTouchListener<ListViewAdapter> touchListener = new SwipeToDismissTouchListener<>( new ListViewAdapter(lv), new SwipeToDismissTouchListener.DismissCallbacks<ListViewAdapter>() { @Override public boolean canDismiss(int position) { return true; } @Override public void onDismiss(ListViewAdapter view, int position) { customAdapter.remove(position); } }); lv.setOnTouchListener(touchListener); lv.setOnScrollListener((AbsListView.OnScrollListener) touchListener.makeScrollListener()); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (touchListener.existPendingDismisses()) { touchListener.undoPendingDismiss(); } else { Toast.makeText(MainActivity.this, "Position " + position, LENGTH_SHORT).show(); } } });
Above code is the heart of this example. When the user swipes left or right, the compiler will execute the above code lines.
Row item of listview is removed when the user swipes left or right. onDismiss() method will be executed when user swipes.
onDismiss() method will call the remove() method from the adapter class.
A position of the listview row item, which is swiped by the user will be sent as a parameter in the remove() method.
You can add your code as per your requirements in this method.
Undo Execution
When user swipes the row, undo option is shown to him. If user changes his mind after swiping the row, he can undo his task by clicking the undo button.
Read below code
if (touchListener.existPendingDismisses()) { touchListener.undoPendingDismiss(); }
When the user clicks on undo text, above code will be executed.
Download Source Code For Android Listview Swipe To Delete
Click on below link to get android studio source code.
[sociallocker]Download Listview Swipe to delete[/sociallocker]
So that is all for android listview swipe to delete tutorial with example.
You can ask your queries in comment without any hesitation.
Thank you and keep sharing our tutorials.