LongPressDetector.kt raw

   1  package io.github.domi04151309.alwayson.custom
   2  
   3  import android.os.Handler
   4  import android.os.Looper
   5  import android.view.MotionEvent
   6  import android.view.ViewConfiguration
   7  
   8  class LongPressDetector(
   9      private val listener: () -> Unit,
  10      private val timeout: Long = ViewConfiguration.getLongPressTimeout().toLong(),
  11  ) {
  12      private var isTouching = false
  13  
  14      fun onTouchEvent(ev: MotionEvent) {
  15          if (ev.action and MotionEvent.ACTION_MASK == MotionEvent.ACTION_DOWN) {
  16              if (!isTouching) {
  17                  isTouching = true
  18                  Handler(Looper.getMainLooper()).postDelayed({
  19                      if (isTouching) listener()
  20                  }, timeout)
  21              }
  22          } else if (ev.action and MotionEvent.ACTION_MASK == MotionEvent.ACTION_UP) {
  23              isTouching = false
  24          }
  25      }
  26  }
  27