- TutorialsBuzz
- ItemTouchHelper :
- Add RecyclerView To XML Layout
- Data Class
- Adapter and ViewHolder For RecyclerView
- ItemTouchHelper CallBack For RecyclerView
- Drag и Swipe в RecyclerView. Часть 1: ItemTouchHelper
- ItemTouchHelper
- Настройка
- Использование ItemTouchHelper и ItemTouchHelper.Callback
- Заключение
- Исходный код
- Step by Step: RecyclerView Swipe to Delete and Undo
- Step 1: ItemTouchHelper.SimpleCallback
- Step 2: Attach ItemTouchHelper to the Recyclerview
- Step 3: Deleting the item
- Step 4: Undo Snackbar
- Swipe to Delete and Undo in Android RecyclerView
- What we are going to build in this article?
- Step by Step Implementation
TutorialsBuzz
RecyclerView is a ViewGroup ,that display a scrolling list of elements based on large data sets (or data that frequently changes) . RecyclerView widget is more flexible and efficient version of ListView .
In the previous tutorial we have seen basic example of recyclerView , In this tutorial deleting items of recyclerView on swiping .
Project Detail
Project Name | RecylerViewSwipeToDelete |
Package | com.tutorialsbuzz.recylerviewswipetodelete |
Min Sdk Version | 22 |
Target Sdk Version | 29 |
Compile Sdk Version | 29 |
Theme | Theme.AppCompat.Light.DarkActionBar |
ItemTouchHelper :
ItemTouchHelper is a utility class to add swipe to dismiss and drag & drop support to RecyclerView. It works with a RecyclerView and a Callback class, which configures what type of interactions are enabled and also receives events when user performs these actions.
Lets see example of swiping (LEFT and RIGHT) items of recyclerView
Add RecyclerView To XML Layout
Create XML Layout activity_main.xml , this will be set as content view for launcher Activity (MainActivity.kt) and add RecyclerView to your layout file .
Data Class
To Load Data Into RecyclerView , We will read JSON File Kept Inside Asset folder and map it to above defined data class
Name field from json matches to respective png file name kept inside drawable .
Adapter and ViewHolder For RecyclerView
ItemTouchHelper CallBack For RecyclerView
- getMovementFlags : Should return a composite flag which defines the enabled move directions in each state (idle, swiping, dragging).Instead of composing this flag manually, you can use makeMovementFlags(int, int) or makeFlag(int, int).For example, if you want it to allow swiping LEFT and RIGHT but only allow starting to swipe by swiping RIGHT, you can return
Источник
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. Первый коммит в основном относится к этой части и немного ко второй.
Источник
Step by Step: RecyclerView Swipe to Delete and Undo
Sep 12, 2018 · 4 min read
Swipe to delete is a prevailing paradigm users are accustomed to on mobile platforms. Adding this functionally is a good way to get your app in line with modern design practices. While there are many libraries that will accomplish this for us, subsequently adding extra bulk to our code, implementing it ourselves is not that complicated. So, let’s get started.
To implement swipe to delete and undo in our RecyclerView we are going to need 3 key components:
- ItemTouchHelper : This attaches to the RecyclerView and watches for swipes.
- ItemTouchHelper.SimpleCallback : This is passed into ItemTouchHelper ’s constructor and contains the code that will run once the item is swiped.
- Snackbar : This is triggered once an item is deleted and gives the user the option to undo the delete.
Step 1: ItemTouchHelper.SimpleCallback
First, let’s create a new class that extends ItemTouchHelper.SimpleCallback and write the constructor.
The fist p arameter in super adds support for dragging the RecyclerView item up or down. We don’t care about that hence the 0. The second parameter tells the ItemTouchHelper (that we will attach to the RecyclerView later) to pass our SimpleCallback information about left and right swipes. The constructor takes a reference to our adapter which we will use to call the deleteItem() function.
Next, we need to override onSwiped() . This is called when an item is swiped off the screen. You also need to override onMove() , but you can leave it as is.
The deleteItem() method does not exist yet but we’ll implement it later in the adapter.
That takes care of the core logic in the SimpleCallback , but we can make it look a little nicer.
Optional Step: Adding the background and Icon
To add our icon and background we just need to override onChildDraw() . This will draw our icon and background in the correct position as our RecyclerView item is swiped across the screen.
Since onChildDraw() is called multiple times per second, let’s try to keep the code as sparse as possible by adding the icon and background as member variables.
Next, in onChildDraw() we need a reference to our ItemView which will be used to calculate the bounds for both the icon and background.
backgroundCornerOffset is used to push the background behind the edge of the parent view so that it appears underneath the rounded corners (as seen in the .gif below). The larger the corner radius of your view, the larger backgroundCornerOffset should be.
Now, we add an if statement that covers the left, right, and no swipe cases. Then, set the bounds for our background in each case respectively and draw it onto the canvas.
To add the icon, define the bounds that are consistent across all swipe cases outside the if statement. Then, set the bounds for each case and draw it onto the canvas.
Alright, that does it for the ItemTouchHelper.SimpleCallback . Checkout the complete code here.
Step 2: Attach ItemTouchHelper to the Recyclerview
In your Activity or Fragment create a new ItemTouchHelper using our SwipeToDeleteCallback and attach it to the RecyclerView .
Step 3: Deleting the item
In the adapter, we need to implement the deleteItem() method we called in SwipeToDeleteCallback earlier. In this method we will first save the removed item into a member variable to be used in case the user wants to undo the delete. We’ll also add a method call to show a Snackbar that we will implement in the next step. Finally, remove the item from our list and update the adapter.
Step 4: Undo Snackbar
Once an item is deleted our undo Snackbar should appear. We want the Snackbar’s action to add the recently removed item back to the list and update the adapter.
And… We’ve done it. Feel free to reach out if you have any questions. Happy coding.
Источник
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
Источник