Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- abstract class ConstraintTouchEvent(
- context: Context,
- attrs: AttributeSet? = null,
- defStyleAttr: Int = 0
- ) : ConstraintLayout(context, attrs, defStyleAttr) {
- abstract fun onClick() : () -> Unit
- abstract fun onLongClick() : () -> Unit
- private var timeDownAction: Long = DEFAULT_LONG
- private var timeUpAction: Long = DEFAULT_LONG
- private var timeDown = DEFAULT_LONG
- private var isClick = false
- private var isLongClick = false
- private var startDx = DEFAULT
- private var endDx = DEFAULT
- private var isNotSwiped = true
- override fun onTouchEvent(event: MotionEvent?): Boolean {
- val eventAction = event?.action
- isClick = false
- isLongClick = false
- timeDown = DEFAULT_LONG
- when (eventAction) {
- MotionEvent.ACTION_UP -> {
- timeUpAction = System.currentTimeMillis()
- val difference = abs(startDx - endDx)
- if(difference <= INFELICITY_SWIPE) {
- startDx = DEFAULT
- endDx = DEFAULT
- isNotSwiped = true
- }
- val timeFocusing = timeUpAction - timeDownAction
- if (timeFocusing >= LONG_CLICK_TIME) {
- isLongClick = true
- } else {
- isClick = true
- }
- }
- MotionEvent.ACTION_DOWN -> {
- isNotSwiped = true
- timeDownAction = System.currentTimeMillis()
- }
- MotionEvent.ACTION_MOVE -> {
- if(startDx == DEFAULT) {
- startDx = event.rawX
- } else {
- endDx = max(endDx,event.rawX)
- }
- isNotSwiped = false
- }
- }
- if (isNotSwiped) {
- if (startDx != DEFAULT && endDx != DEFAULT) {
- startDx = DEFAULT
- endDx = DEFAULT
- } else {
- if (isLongClick) {
- onLongClick().invoke()
- }
- if (isClick) {
- onClick().invoke()
- }
- }
- }
- return true
- }
- private companion object {
- private const val LONG_CLICK_TIME = 600L
- private const val DEFAULT = -1.0f
- private const val DEFAULT_LONG = -1L
- private const val INFELICITY_SWIPE = 5.0f
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement