- Drag и Swipe в RecyclerView. Часть 1: ItemTouchHelper
- ItemTouchHelper
- Настройка
- Использование ItemTouchHelper и ItemTouchHelper.Callback
- Заключение
- Исходный код
- Swipe to Delete and Undo in Android RecyclerView
- What we are going to build in this article?
- Step by Step Implementation
- Android RecyclerView Swipe To Delete Example Button And Undo
- Step 1. Create a new project.
- Step 2. Make row item layout
- Step 3. Update gradle file
- Step 4. Making Model Class
- Step 5. Creating Adapter
- Understanding removeItem()
- Understanding resoreItem()
- Step 6. Updating MainActivity
- Understanding unableSwipe() method
- Download Source Code For Android RecyclerView Swipe To Delete
- One thought on “Android RecyclerView Swipe To Delete Example Button And Undo”
- Android Listview Swipe To Delete Example Tutorial Step By Step
- Step 1. Make a new project.
- Step 2. Adding dimens file
- Step 3. Updating colors.xml
- Step 4. Create listview row layout
- Step 5. Add Library to build.gradle(Module: app)
- Step 6. Adding Images
- Step 7. Making Model
- Step 8. Preparing Custom Adapter
- Step 9. Updating Main Activity
- Understanding the main logic
- Undo Execution
- Download Source Code For Android Listview Swipe To Delete
Drag и Swipe в RecyclerView. Часть 1: ItemTouchHelper
Существует множество обучающих материалов, библиотек и примеров реализации drag & drop и swipe-to-dismiss в Android c использованием RecyclerView. В большинстве из них по-прежнему используются устаревший View.OnDragListener и подход SwipeToDismiss, разработанный Романом Нуриком. Хотя уже доступны новые и более эффективные методы. Совсем немногие используют новейшие API, зачастую полагаясь на GestureDetectors и onInterceptTouchEvent или же на другие более сложные имплементации. На самом деле существует очень простой способ добавить эти функции в RecyclerView . Для этого требуется всего лишь один класс, который к тому же является частью Android Support Library.
ItemTouchHelper
ItemTouchHelper — это мощная утилита, которая позаботится обо всём, что необходимо сделать, чтобы добавить функции drag & drop и swipe-to-dismiss в RecyclerView . Эта утилита является подклассом RecyclerView.ItemDecoration, благодаря чему её легко добавить практически к любому существующему LayoutManager и адаптеру. Она также работает с анимацией элементов и предоставляет возможность перетаскивать элементы одного типа на другое место в списке и многое другое. В этой статье я продемонстрирую простую реализацию ItemTouchHelper . Позже, в рамках этой серии статей, мы расширим рамки и рассмотрим остальные возможности.
Примечание. Хотите сразу увидеть результат? Загляните на Github: Android-ItemTouchHelper-Demo. Первый коммит относится к этой статье. Демо .apk -файл можно скачать здесь.
Настройка
Сперва нам нужно настроить RecyclerView . Если вы ещё этого не сделали, добавьте зависимость RecyclerView в свой файл build.gradle .
ItemTouchHelper будет работать практически с любыми RecyclerView.Adapter и LayoutManager , но эта статья базируется на примерах, использующих эти файлы.
Использование ItemTouchHelper и ItemTouchHelper.Callback
Чтобы использовать ItemTouchHelper , вам необходимо создать ItemTouchHelper.Callback. Это интерфейс, который позволяет отслеживать действия перемещения (англ. move) и смахивания (англ. swipe). Кроме того, здесь вы можете контролировать состояние выделенного view -компонента и переопределять анимацию по умолчанию. Существует вспомогательный класс, который вы можете использовать, если хотите использовать базовую имплементацию, — SimpleCallback. Но для того, чтобы понять, как это работает на практике, сделаем всё самостоятельно.
Основные функции интерфейса, которые мы должны переопределить, чтобы включить базовый функционал drag & drop и swipe-to-dismiss:
Мы также будем использовать несколько вспомогательных методов:
Рассмотрим их поочередно.
ItemTouchHelper позволяет легко определить направление события. Вам нужно переопределить метод getMovementFlags() , чтобы указать, какие направления для перетаскивания будут поддерживаться. Для создания возвращаемых флагов используйте вспомогательный метод ItemTouchHelper.makeMovementFlags(int, int) . В этом примере мы разрешаем перетаскивание и смахивание в обоих направлениях.
ItemTouchHelper можно использовать только для перетаскивания без функционала смахивания (или наоборот), поэтому вы должны точно указать, какие функции должны поддерживаться. Метод isLongPressDragEnabled() должен возвращать значение true , чтобы поддерживалось перетаскивание после длительного нажатия на элемент RecyclerView . В качестве альтернативы можно вызвать метод ItemTouchHelper.startDrag(RecyclerView.ViewHolder) , чтобы начать перетаскивание вручную. Рассмотрим этот вариант позже.
Чтобы разрешить смахивание после касания где угодно в рамках view -компонента, просто верните значение true из метода isItemViewSwipeEnabled() . В качестве альтернативы можно вызвать метод ItemTouchHelper.startSwipe(RecyclerView.ViewHolder) , чтобы начать смахивание вручную.
Следующие два метода, onMove() и onSwiped() , необходимы для того, чтобы уведомить об обновлении данных. Итак, сначала мы создадим интерфейс, который позволит передать эти события по цепочке вызовов.
Самый простой способ сделать это — сделать так, чтобы RecyclerListAdapter имплементировал слушателя.
Очень важно вызвать методы notifyItemRemoved() и notifyItemMoved() , чтобы адаптер увидел изменения. Также нужно отметить, что мы меняем позицию элемента каждый раз, когда view -компонент смещается на новый индекс, а не в самом конце перемещения (событие «drop»).
Теперь мы можем вернуться к созданию SimpleItemTouchHelperCallback , поскольку нам всё ещё необходимо переопределить методы onMove() и onSwiped() . Сначала добавьте конструктор и поле для адаптера:
Затем переопределите оставшиеся события и сообщите об этом адаптеру:
В результате класс Callback должен выглядеть примерно так:
Когда Callback готов, мы можем создать ItemTouchHelper и вызвать метод attachToRecyclerView(RecyclerView) (например, в MainFragment.java):
После запуска должно получиться приблизительно следующее:
Заключение
Это максимально упрощённая реализация ItemTouchHelper . Тем не менее, вы можете заметить, что вам не обязательно использовать стороннюю библиотеку для реализации стандартных действий drag & drop и swipe-to-dismiss в RecyclerView . В следующей части мы уделим больше внимания внешнему виду элементов в момент перетаскивания или смахивания.
Исходный код
Я создал проект на GitHub для демонстрации того, о чём рассказывается в этой серии статей: Android-ItemTouchHelper-Demo. Первый коммит в основном относится к этой части и немного ко второй.
Источник
Swipe to Delete and Undo in Android RecyclerView
We have seen many apps having a RecyclerView present in them and along with that, we have seen many functionalities in that RecyclerView for swipe to delete and many more. We have seen this type of feature in Gmail apps where we can swipe or item right or left to delete or add to the archive. In this article, we will take a look at the implementation of Swipe to Delete RecyclerView items in Android with Undo functionality in it.
What we are going to build in this article?
We will be building a simple application in which we will be displaying a simple RecyclerView which displays a list of courses along with its description and we will be adding functionality for swipe to delete and undo to it. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include:
- Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view.
- View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data.
- Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View.
Step 2: Create a Card Layout for RecyclerView Card Items
Источник
Android RecyclerView Swipe To Delete Example Button And Undo
Android RecyclerView Swipe To Delete Example Tutorial is explained here.
We will make a recyclerview such that user swipe to show button, which will delete the row.
Android RecyclerView Swipe to delete example is similar like gmail app.
We will also implement an UNDO feature, which will restore the deleted row item.
First, check the output of the example, then we will create it with android studio.
Step 1. Create a new project.
Always try to create new project with empty activity in android studio.
Step 2. Make row item layout
Prepare new layout resource file named rv_item.xml
Copy following source code in it
This layout file rv_item.xml file represents the layout for each row of recyclerview.
Here, we will create simple row item with just one text in it.
TextView is added to show the name of the row item.
Step 3. Update gradle file
Add below lines in your build.module(Module:app) file
Above three lines add the required classes for recyclerview, cardview and material design respectively.
Step 4. Making Model Class
Make a new JAVA class and give it a name Model.java
Add below code in it
Model class is something like a data transporter for recyclerview.
An object of model class is created for each row item of recyclerview then, all these objects are stored in an ArrayList.
Finally, ArayList will populate the recyclerview in Adapter class.
Step 5. Creating Adapter
A java class named Adapter.java will contain below source code. Go ahead and make new java class.
Adapter will populate the RecyclerView with the help of ArrayList of Model objets.
Two methods of adapter are important here.
Understanding removeItem()
This method will remove the row item when user swipes left or right.
Look at below code
When user swipes left or right, this method will be called from MainActivity.java class along with the position as a parameter.
You can see in above code that an object of model class is removed from ArrayList who is present at position given by parameter.
Understanding resoreItem()
This method will restore the deleted item, when user clicks on UNDO.
Look at following code
When user clicks on UNDO, a model object which was deleted and a position will be passed from Main Activity.
Then, model object will be added at the required position which was also passed from Main Activity as a parameter.
Step 6. Updating MainActivity
Update activity_main.xml as below
Update MainActivity.java class as following
Understanding unableSwipe() method
Refer below code
This method will detect the swipe movement(left or right) of the user.
Then method will decide whether user have swipe left or right. Here, we are deleting row item on both swipe, but you can update them as per your requirement.
After removing the row item, a snackbar will be shown at the bottom of the screen.
This snackbar contains the UNDO button, which can be used to restore the deleted row item.
So it was all about creating Swipe to delete in recyclerview.
If you want to use third party library, then you can use below github library.
But, it is better not to use third party library as it increases the apk file size.
Share our articles with other learners to help them in their journey.
Cheers and Happy coding! 🙂
Download Source Code For Android RecyclerView Swipe To Delete
Click on below link to download android studio source code.
One thought on “Android RecyclerView Swipe To Delete Example Button And Undo”
it removes my item from the list but how can i remove that item from my actual model class
Источник
Android Listview Swipe To Delete Example Tutorial Step By Step
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
Step 3. Updating colors.xml
Update colors.xml file with below
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
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
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
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
Step 8. Preparing Custom Adapter
Make a new java class with name CustomAdapter.java
Add following into it
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
Update MainActivity.java file as below
Understanding the main logic
Look closely at following snippet from Main Activity
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
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.
Источник