-
public abstract class ItemTouchHelper.Callback
This class is the contract between ItemTouchHelper and your application. It lets you controlwhich touch behaviors are enabled per each ViewHolder and also receive callbacks when userperforms these actions.
To control which actions user can take on each view, you should override getMovementFlags and return appropriate setof direction flags. (LEFT, RIGHT, START, END, UP, DOWN). You can use makeMovementFlags to easily construct it. Alternatively, you can use SimpleCallback.
If user drags an item, ItemTouchHelper will call onMove(recyclerView, dragged, target).Upon receiving this callback, you should move the item from the old position(
{@code dragged.getAdapterPosition()}
) to new position ({@code target.getAdapterPosition()}
)in your adapter and also call notifyItemMoved.To control where a View can be dropped, you can override canDropOver. When adragging View overlaps multiple other views, Callback chooses the closest View with whichdragged View might have changed positions. Although this approach works for many use cases,if you have a custom LayoutManager, you can override chooseDropTarget to select acustom drop target.When a View is swiped, ItemTouchHelper animates it until it goes out of bounds, then calls onSwiped. At this point, you should update youradapter (e.g. remove the item) and call related Adapter#notify event.
-
-
Field Summary
Fields Modifier and Type Field Description public final static int
DEFAULT_DRAG_ANIMATION_DURATION
public final static int
DEFAULT_SWIPE_ANIMATION_DURATION
-
Method Summary
Modifier and Type Method Description static ItemTouchUIUtil
getDefaultUIUtil()
Returns the ItemTouchUIUtil that is used by the Callback class forvisualchanges on Views in response to user interactions. static int
convertToRelativeDirection(int flags, int layoutDirection)
Replaces a movement direction with its relative version by taking layout direction intoaccount. static int
makeMovementFlags(int dragFlags, int swipeFlags)
Convenience method to create movement flags. static int
makeFlag(int actionState, int directions)
Shifts the given direction flags to the offset of the given action state. abstract int
getMovementFlags(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder)
Should return a composite flag which defines the enabled move directions in each state(idle, swiping, dragging). int
convertToAbsoluteDirection(int flags, int layoutDirection)
Converts a given set of flags to absolution direction which means START and END are replaced with LEFT and RIGHT depending on the layoutdirection. boolean
canDropOver(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder current, @NonNull() RecyclerView.ViewHolder target)
Return true if the current ViewHolder can be dropped over the the target ViewHolder. abstract boolean
onMove(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder, @NonNull() RecyclerView.ViewHolder target)
Called when ItemTouchHelper wants to move the dragged item from its old position tothe new position. boolean
isLongPressDragEnabled()
Returns whether ItemTouchHelper should start a drag and drop operation if an item islong pressed. boolean
isItemViewSwipeEnabled()
Returns whether ItemTouchHelper should start a swipe operation if a pointer is swipedover the View. int
getBoundingBoxMargin()
When finding views under a dragged view, by default, ItemTouchHelper searches for viewsthat overlap with the dragged View. float
getSwipeThreshold(@NonNull() RecyclerView.ViewHolder viewHolder)
Returns the fraction that the user should move the View to be considered as swiped.The fraction is calculated with respect to RecyclerView's bounds. float
getMoveThreshold(@NonNull() RecyclerView.ViewHolder viewHolder)
Returns the fraction that the user should move the View to be considered as it isdragged. float
getSwipeEscapeVelocity(float defaultValue)
Defines the minimum velocity which will be considered as a swipe action by the user. float
getSwipeVelocityThreshold(float defaultValue)
Defines the maximum velocity ItemTouchHelper will ever calculate for pointer movements. RecyclerView.ViewHolder
chooseDropTarget(@NonNull() RecyclerView.ViewHolder selected, @NonNull() List<RecyclerView.ViewHolder> dropTargets, int curX, int curY)
Called by ItemTouchHelper to select a drop target from the list of ViewHolders thatare under the dragged View. abstract void
onSwiped(@NonNull() RecyclerView.ViewHolder viewHolder, int direction)
Called when a ViewHolder is swiped by the user. void
onSelectedChanged(@Nullable() RecyclerView.ViewHolder viewHolder, int actionState)
Called when the ViewHolder swiped or dragged by the ItemTouchHelper is changed. void
onMoved(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder, int fromPos, @NonNull() RecyclerView.ViewHolder target, int toPos, int x, int y)
Called when onMove returns true. void
clearView(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder)
Called by the ItemTouchHelper when the user interaction with an element is over and italso completed its animation. void
onChildDraw(@NonNull() Canvas c, @NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive)
Called by ItemTouchHelper on RecyclerView's onDraw callback. void
onChildDrawOver(@NonNull() Canvas c, @NonNull() RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive)
Called by ItemTouchHelper on RecyclerView's onDraw callback. long
getAnimationDuration(@NonNull() RecyclerView recyclerView, int animationType, float animateDx, float animateDy)
Called by the ItemTouchHelper when user action finished on a ViewHolder and now the Viewwill be animated to its final position. int
interpolateOutOfBoundsScroll(@NonNull() RecyclerView recyclerView, int viewSize, int viewSizeOutOfBounds, int totalSize, long msSinceStartScroll)
Called by the ItemTouchHelper when user is dragging a view out of bounds. -
-
Method Detail
-
getDefaultUIUtil
@NonNull() static ItemTouchUIUtil getDefaultUIUtil()
Returns the ItemTouchUIUtil that is used by the Callback class forvisualchanges on Views in response to user interactions. ItemTouchUIUtil has differentimplementations for different platform versions.
By default, Callback applies these changes on itemView.
For example, if you have a use case where you only want the text to move when userswipes over the view, you can do the following:
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder){ getDefaultUIUtil().clearView(((ItemTouchViewHolder) viewHolder).textView); } public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { if (viewHolder != null){ getDefaultUIUtil().onSelected(((ItemTouchViewHolder) viewHolder).textView); } } public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { getDefaultUIUtil().onDraw(c, recyclerView, ((ItemTouchViewHolder) viewHolder).textView, dX, dY, actionState, isCurrentlyActive); return true; } public void onChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { getDefaultUIUtil().onDrawOver(c, recyclerView, ((ItemTouchViewHolder) viewHolder).textView, dX, dY, actionState, isCurrentlyActive); return true; }
-
convertToRelativeDirection
static int convertToRelativeDirection(int flags, int layoutDirection)
Replaces a movement direction with its relative version by taking layout direction intoaccount.
- Parameters:
flags
- The flag value that include any number of movement flags.layoutDirection
- The layout direction of the View.
-
makeMovementFlags
static int makeMovementFlags(int dragFlags, int swipeFlags)
Convenience method to create movement flags.
For instance, if you want to let your items be drag & dropped vertically and swipedleft to be dismissed, you can call this method with:
makeMovementFlags(UP | DOWN, LEFT);
- Parameters:
dragFlags
- The directions in which the item can be dragged.swipeFlags
- The directions in which the item can be swiped.
-
makeFlag
static int makeFlag(int actionState, int directions)
Shifts the given direction flags to the offset of the given action state.
- Parameters:
actionState
- The action state you want to get flags in.directions
- The direction flags.
-
getMovementFlags
abstract int getMovementFlags(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder)
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 or makeFlag.
This flag is composed of 3 sets of 8 bits, where first 8 bits are for IDLE state, next8 bits are for SWIPE state and third 8 bits are for DRAG state.Each 8 bit sections can be constructed by simply OR'ing direction flags defined in ItemTouchHelper.
For example, if you want it to allow swiping LEFT and RIGHT but only allow starting toswipe by swiping RIGHT, you can return:
This means, allow right movement while IDLE and allow right and left movement whileswiping.makeFlag(ACTION_STATE_IDLE, RIGHT) | makeFlag(ACTION_STATE_SWIPE, LEFT | RIGHT);
- Parameters:
recyclerView
- The RecyclerView to which ItemTouchHelper is attached.viewHolder
- The ViewHolder for which the movement information is necessary.
-
convertToAbsoluteDirection
int convertToAbsoluteDirection(int flags, int layoutDirection)
Converts a given set of flags to absolution direction which means START and END are replaced with LEFT and RIGHT depending on the layoutdirection.
- Parameters:
flags
- The flag value that include any number of movement flags.layoutDirection
- The layout direction of the RecyclerView.
-
canDropOver
boolean canDropOver(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder current, @NonNull() RecyclerView.ViewHolder target)
Return true if the current ViewHolder can be dropped over the the target ViewHolder.
This method is used when selecting drop target for the dragged View. After Views areeliminated either via bounds check or via this method, resulting set of views will bepassed to chooseDropTarget.
Default implementation returns true.
- Parameters:
recyclerView
- The RecyclerView to which ItemTouchHelper is attached to.current
- The ViewHolder that user is dragging.target
- The ViewHolder which is below the dragged ViewHolder.
-
onMove
abstract boolean onMove(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder, @NonNull() RecyclerView.ViewHolder target)
Called when ItemTouchHelper wants to move the dragged item from its old position tothe new position.
If this method returns true, ItemTouchHelper assumes
{@code viewHolder}
has been movedto the adapter position of{@code target}
ViewHolder( ViewHolder#getAdapterPositionInRecyclerView()).If you don't support drag & drop, this method will never be called.
- Parameters:
recyclerView
- The RecyclerView to which ItemTouchHelper is attached to.viewHolder
- The ViewHolder which is being dragged by the user.target
- The ViewHolder over which the currently active item is beingdragged.
-
isLongPressDragEnabled
boolean isLongPressDragEnabled()
Returns whether ItemTouchHelper should start a drag and drop operation if an item islong pressed.
Default value returns true but you may want to disable this if you want to startdragging on a custom view touch using startDrag.
-
isItemViewSwipeEnabled
boolean isItemViewSwipeEnabled()
Returns whether ItemTouchHelper should start a swipe operation if a pointer is swipedover the View.
Default value returns true but you may want to disable this if you want to startswiping on a custom view touch using startSwipe.
-
getBoundingBoxMargin
int getBoundingBoxMargin()
When finding views under a dragged view, by default, ItemTouchHelper searches for viewsthat overlap with the dragged View. By overriding this method, you can extend or shrinkthe search box.
-
getSwipeThreshold
float getSwipeThreshold(@NonNull() RecyclerView.ViewHolder viewHolder)
Returns the fraction that the user should move the View to be considered as swiped.The fraction is calculated with respect to RecyclerView's bounds.
Default value is .5f, which means, to swipe a View, user must move the View at leasthalf of RecyclerView's width or height, depending on the swipe direction.
- Parameters:
viewHolder
- The ViewHolder that is being dragged.
-
getMoveThreshold
float getMoveThreshold(@NonNull() RecyclerView.ViewHolder viewHolder)
Returns the fraction that the user should move the View to be considered as it isdragged. After a view is moved this amount, ItemTouchHelper starts checking for Viewsbelow it for a possible drop.
- Parameters:
viewHolder
- The ViewHolder that is being dragged.
-
getSwipeEscapeVelocity
float getSwipeEscapeVelocity(float defaultValue)
Defines the minimum velocity which will be considered as a swipe action by the user.
You can increase this value to make it harder to swipe or decrease it to make it easier.Keep in mind that ItemTouchHelper also checks the perpendicular velocity and makes surecurrent direction velocity is larger then the perpendicular one. Otherwise, user'smovement is ambiguous. You can change the threshold by overriding getSwipeVelocityThreshold.
The velocity is calculated in pixels per second.
The default framework value is passed as a parameter so that you can modify it with amultiplier.
- Parameters:
defaultValue
- The default value (in pixels per second) used by theItemTouchHelper.
-
getSwipeVelocityThreshold
float getSwipeVelocityThreshold(float defaultValue)
Defines the maximum velocity ItemTouchHelper will ever calculate for pointer movements.
To consider a movement as swipe, ItemTouchHelper requires it to be larger than theperpendicular movement. If both directions reach to the max threshold, none of them willbe considered as a swipe because it is usually an indication that user rather tried toscroll then swipe.
The velocity is calculated in pixels per second.
You can customize this behavior by changing this method. If you increase the value, itwill be easier for the user to swipe diagonally and if you decrease the value, user willneed to make a rather straight finger movement to trigger a swipe.
- Parameters:
defaultValue
- The default value(in pixels per second) used by the ItemTouchHelper.
-
chooseDropTarget
RecyclerView.ViewHolder chooseDropTarget(@NonNull() RecyclerView.ViewHolder selected, @NonNull() List<RecyclerView.ViewHolder> dropTargets, int curX, int curY)
Called by ItemTouchHelper to select a drop target from the list of ViewHolders thatare under the dragged View.
Default implementation filters the View with which dragged item have changed positionin the drag direction. For instance, if the view is dragged UP, it compares the
view.getTop()
of the two views before and after drag started. If that valueis different, the target view passes the filter.Among these Views which pass the test, the one closest to the dragged view is chosen.
This method is called on the main thread every time user moves the View. If you want tooverride it, make sure it does not do any expensive operations.
- Parameters:
selected
- The ViewHolder being dragged by the user.dropTargets
- The list of ViewHolder that are under the dragged View andcandidate as a drop.curX
- The updated left value of the dragged View after drag translationsare applied.curY
- The updated top value of the dragged View after drag translationsare applied.
-
onSwiped
abstract void onSwiped(@NonNull() RecyclerView.ViewHolder viewHolder, int direction)
Called when a ViewHolder is swiped by the user.
If you are returning relative directions (START , END) from the getMovementFlags method, this methodwill also use relative directions. Otherwise, it will use absolute directions.
If you don't support swiping, this method will never be called.
ItemTouchHelper will keep a reference to the View until it is detached fromRecyclerView.As soon as it is detached, ItemTouchHelper will call clearView.
- Parameters:
viewHolder
- The ViewHolder which has been swiped by the user.direction
- The direction to which the ViewHolder is swiped.
-
onSelectedChanged
void onSelectedChanged(@Nullable() RecyclerView.ViewHolder viewHolder, int actionState)
Called when the ViewHolder swiped or dragged by the ItemTouchHelper is changed.
If you override this method, you should call super.- Parameters:
viewHolder
- The new ViewHolder that is being swiped or dragged.actionState
- One of ACTION_STATE_IDLE,ACTION_STATE_SWIPE orACTION_STATE_DRAG.
-
onMoved
void onMoved(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder, int fromPos, @NonNull() RecyclerView.ViewHolder target, int toPos, int x, int y)
Called when onMove returns true.
ItemTouchHelper does not create an extra Bitmap or View while dragging, instead, itmodifies the existing View. Because of this reason, it is important that the View isstill part of the layout after it is moved. This may not work as intended when swappedViews are close to RecyclerView bounds or there are gaps between them (e.g. other Viewswhich were not eligible for dropping over).
This method is responsible to give necessary hint to the LayoutManager so that it willkeep the View in visible area. For example, for LinearLayoutManager, this is as simpleas calling scrollToPositionWithOffset.Default implementation calls scrollToPosition if the View'snew position is likely to be out of bounds.
It is important to ensure the ViewHolder will stay visible as otherwise, it might beremoved by the LayoutManager if the move causes the View to go out of bounds. In thatcase, drag will end prematurely.
- Parameters:
recyclerView
- The RecyclerView controlled by the ItemTouchHelper.viewHolder
- The ViewHolder under user's control.fromPos
- The previous adapter position of the dragged item (before it wasmoved).target
- The ViewHolder on which the currently active item has been dropped.toPos
- The new adapter position of the dragged item.x
- The updated left value of the dragged View after drag translationsare applied.y
- The updated top value of the dragged View after drag translationsare applied.
-
clearView
void clearView(@NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder)
Called by the ItemTouchHelper when the user interaction with an element is over and italso completed its animation.
This is a good place to clear all changes on the View that was done in onSelectedChanged, onChildDraw or onChildDrawOver.
- Parameters:
recyclerView
- The RecyclerView which is controlled by the ItemTouchHelper.viewHolder
- The View that was interacted by the user.
-
onChildDraw
void onChildDraw(@NonNull() Canvas c, @NonNull() RecyclerView recyclerView, @NonNull() RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive)
Called by ItemTouchHelper on RecyclerView's onDraw callback.
If you would like to customize how your View's respond to user interactions, this isa good place to override.
Default implementation translates the child by the given
dX
,dY
.ItemTouchHelper also takes care of drawing the child after other children if it is beingdragged. This is done using child re-ordering mechanism. On platforms prior to L, thisisachieved via getChildDrawingOrder and on Land after, it changes View's elevation value to be greater than all other children.)- Parameters:
c
- The canvas which RecyclerView is drawing its childrenrecyclerView
- The RecyclerView to which ItemTouchHelper is attached toviewHolder
- The ViewHolder which is being interacted by the User or it wasinteracted and simply animating to its original positiondX
- The amount of horizontal displacement caused by user's actiondY
- The amount of vertical displacement caused by user's actionactionState
- The type of interaction on the View.isCurrentlyActive
- True if this view is currently being controlled by the user orfalse it is simply animating back to its original state.
-
onChildDrawOver
void onChildDrawOver(@NonNull() Canvas c, @NonNull() RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive)
Called by ItemTouchHelper on RecyclerView's onDraw callback.
If you would like to customize how your View's respond to user interactions, this isa good place to override.
Default implementation translates the child by the given
dX
,dY
.ItemTouchHelper also takes care of drawing the child after other children if it is beingdragged. This is done using child re-ordering mechanism. On platforms prior to L, thisisachieved via getChildDrawingOrder and on Land after, it changes View's elevation value to be greater than all other children.)- Parameters:
c
- The canvas which RecyclerView is drawing its childrenrecyclerView
- The RecyclerView to which ItemTouchHelper is attached toviewHolder
- The ViewHolder which is being interacted by the User or it wasinteracted and simply animating to its original positiondX
- The amount of horizontal displacement caused by user's actiondY
- The amount of vertical displacement caused by user's actionactionState
- The type of interaction on the View.isCurrentlyActive
- True if this view is currently being controlled by the user orfalse it is simply animating back to its original state.
-
getAnimationDuration
long getAnimationDuration(@NonNull() RecyclerView recyclerView, int animationType, float animateDx, float animateDy)
Called by the ItemTouchHelper when user action finished on a ViewHolder and now the Viewwill be animated to its final position.
Default implementation uses ItemAnimator's duration values. If
animationType
is ANIMATION_TYPE_DRAG, it returns getMoveDuration, otherwise, it returns getRemoveDuration. If RecyclerView does not haveany RecyclerView.ItemAnimator attached, this method returns{@code DEFAULT_DRAG_ANIMATION_DURATION}
or{@code DEFAULT_SWIPE_ANIMATION_DURATION}
depending on the animation type.- Parameters:
recyclerView
- The RecyclerView to which the ItemTouchHelper is attached to.animationType
- The type of animation.animateDx
- The horizontal distance that the animation will offsetanimateDy
- The vertical distance that the animation will offset
-
interpolateOutOfBoundsScroll
int interpolateOutOfBoundsScroll(@NonNull() RecyclerView recyclerView, int viewSize, int viewSizeOutOfBounds, int totalSize, long msSinceStartScroll)
Called by the ItemTouchHelper when user is dragging a view out of bounds.
You can override this method to decide how much RecyclerView should scroll in responseto this action. Default implementation calculates a value based on the amount of Viewout of bounds and the time it spent there. The longer user keeps the View out of bounds,the faster the list will scroll. Similarly, the larger portion of the View is out ofbounds, the faster the RecyclerView will scroll.
- Parameters:
recyclerView
- The RecyclerView instance to which ItemTouchHelper isattached to.viewSize
- The total size of the View in scroll direction, excludingitem decorations.viewSizeOutOfBounds
- The total size of the View that is out of bounds.totalSize
- The total size of RecyclerView in the scroll direction.msSinceStartScroll
- The time passed since View is kept out of bounds.
-
-
-
-