-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwipeToDelete.kt
More file actions
95 lines (80 loc) · 2.97 KB
/
SwipeToDelete.kt
File metadata and controls
95 lines (80 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.kedia.swipetodelete
import android.graphics.Canvas
import android.graphics.Color
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.RIGHT
import androidx.recyclerview.widget.RecyclerView
import java.lang.Exception
object SwipeToDelete {
fun RecyclerView.addSwipeToDelete(
list: List<DIRECTION> = emptyList(),
listener: OnSwiped? = null,
@ColorInt colorOneInt: Int? = null,
@ColorInt colorTwoInt: Int? = null
) {
var swipeDirs = RIGHT
for (element in list) {
if (element != DIRECTION.RIGHT) {
swipeDirs = swipeDirs or DIRECTION.valueOf(element.name).direction
}
}
val simpleCallback = object : ItemTouchHelper.SimpleCallback(0 , swipeDirs) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
listener?.swipeToDelete(adapterPosition = viewHolder.adapterPosition)
this@addSwipeToDelete.adapter?.notifyItemRemoved(viewHolder.adapterPosition)
}
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
c.clipRect(0f, viewHolder.itemView.top.toFloat(),
dX, viewHolder.itemView.bottom.toFloat())
if (colorTwoInt != null && colorOneInt == null)
throw Exception("Color One cannot be null if Color Two is non null")
if (colorTwoInt == null) {
colorOneInt?.apply { c.drawColor(this) }
} else {
if(dX < width / 2)
colorOneInt?.apply { c.drawColor(this) }
else
colorTwoInt?.apply { c.drawColor(this) }
}
super.onChildDraw(
c,
recyclerView,
viewHolder,
dX,
dY,
actionState,
isCurrentlyActive
)
}
}
ItemTouchHelper(simpleCallback).attachToRecyclerView(this)
}
private fun Float.isPositive(): Boolean {
return this > 0
}
interface OnSwiped {
fun swipeToDelete(adapterPosition: Int)
}
enum class DIRECTION(val direction: Int) {
UP (ItemTouchHelper.UP),
DOWN(ItemTouchHelper.DOWN),
RIGHT(ItemTouchHelper.RIGHT),
LEFT(ItemTouchHelper.LEFT)
}
}