I have a RecyclerView with items inside like this:
I use ItemTouchHelper.SimpleCallback
to listen for swipe and onChildDraw() to draw a canvas when items are swiped:
A bit more swipe:
I want to simulate a swipe (at run time) just on first item inside the list of items; I need first item to go (more or less ) -100 px on its X axis and then go back to original position. How to achieve this?
In the above code we have added recycler view to window manger as relative parent layout and add FloatingActionButton. FloatingActionButton supports CoordinatorLayout. So we have used parent layout is CoordinatorLayout. When you click on FloatingActionButton, it will scroll to top position.
I created some utility method in case someone needs it
import android.animation.ValueAnimator
import android.os.SystemClock
import android.view.MotionEvent
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
/**
* @author Oleh Haidaienko
* @since 29.07.2020
*/
object SwipeUtils {
/**
* Programmatically swipe RecyclerView item
* @param recyclerView RecyclerView which item will be swiped
* @param index Position of item
* @param distance Swipe distance
* @param direction Swipe direction, can be [ItemTouchHelper.START] or [ItemTouchHelper.END]
* @param time Animation time in milliseconds
*/
fun swipeRecyclerViewItem(
recyclerView: RecyclerView,
index: Int,
distance: Int,
direction: Int,
time: Long
) {
val childView = recyclerView.getChildAt(index) ?: return
val x = childView.width / 2F
val viewLocation = IntArray(2)
childView.getLocationInWindow(viewLocation)
val y = (viewLocation[1] + childView.height) / 2F
val downTime = SystemClock.uptimeMillis()
recyclerView.dispatchTouchEvent(
MotionEvent.obtain(
downTime,
downTime,
MotionEvent.ACTION_DOWN,
x,
y,
0
)
)
ValueAnimator.ofInt(0, distance).apply {
duration = time
addUpdateListener {
val dX = it.animatedValue as Int
val mX = when (direction) {
ItemTouchHelper.END -> x + dX
ItemTouchHelper.START -> x - dX
else -> 0F
}
recyclerView.dispatchTouchEvent(
MotionEvent.obtain(
downTime,
SystemClock.uptimeMillis(),
MotionEvent.ACTION_MOVE,
mX,
y,
0
)
)
}
}.start()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With