【问题标题】:How to get long click events on Android main thread with a delay using Kotlin Coroutines如何使用 Kotlin Coroutines 在 Android 主线程上延迟获得长点击事件
【发布时间】:2021-08-16 20:53:15
【问题描述】:

我所拥有的解决方案可能不像使用 Handler 编写的那样优雅,但给了我想要的体验,只要按下按钮,长点击事件就会发生一些 ui 进程并且该进程应该会延迟一点,因为事件流很快,我想用 Kotlin 的协程 API 做类似的体验。

button.setOnLongClickListener {
        val handler = Handler(Looper.myLooper()!!)
        val runnable: Runnable = object : Runnable {
            override fun run() {
                handler.removeCallbacks(this)
                if (nextButton.isPressed) {
                    Log.e("Press", "Thread name: ${handler.looper.thread.name} ")
                    handler.postDelayed(this, 500)
                }
            }
        }
        handler.postDelayed(runnable, 0)
        true
    }

【问题讨论】:

    标签: android kotlin coroutine


    【解决方案1】:

    可以这样做。

    button.setOnLongClickListener {
        GlobalScope.launch(Dispatchers.Main) {
            while (isActive && nextButton.isPressed) {
                Log.e("Press", "Thread name: ${handler.looper.thread.name} ")
                delay(500)
            }
        }
        true
    }
    

    注意:不要像我一样使用GlobalScope!使用lifecycleScope 或任何有意义的东西。

    【讨论】:

    • 稍微埋点lede...如果是Activity,请使用lifecycleScope,如果是Fragment,请使用viewLifecycleScope。我提出它是因为我看到 GlobalScope 在许多问题和答案中不应该被使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多