LoginSignup
0
0

More than 1 year has passed since last update.

【Kotlin】Viewを長押し時、クリックイベントをリピートする処理を追加する

Posted at

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
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0