Viewを長押しした時にクリックイベントをリピートする処理を追加したく、
以下のJavaコードをKotlinに変換したコードを作成したため、備忘録として残しておきます。
環境
- Android 10
- Android Studio 4.1.3
コード
LongClickRepeatAdapter.Kt
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View
class LongClickRepeatAdapter {
/**
* 長押し時のリピート処理間隔
*/
companion object {
private const val REPEAT_INTERVAL: Long = 100
}
/**
* 引数のViewに長押しリピート処理を付加する
* @param view View
*/
@SuppressLint("ClickableViewAccessibility")
fun bless(view: View) {
val handler = Handler(Looper.getMainLooper())
val isContinue = BooleanWrapper()
val repeatRunnable = object : Runnable {
override fun run() {
if (!isContinue.value) return
view.performClick()
handler.postDelayed(this, REPEAT_INTERVAL)
}
}
view.setOnLongClickListener {
isContinue.value = true
handler.post(repeatRunnable)
return@setOnLongClickListener true
}
view.setOnTouchListener { _, motionEvent ->
if (motionEvent.action == MotionEvent.ACTION_UP || motionEvent.action == MotionEvent.ACTION_CANCEL) {
isContinue.value = false
handler.removeCallbacks(repeatRunnable)
}
return@setOnTouchListener false
}
}
private class BooleanWrapper {
var value = false
}
}