[英]How to execute button.setOnTouchListener when some conditions are met (Kotlin)
我制作了按鈕並給它 touchlistener。
當我按住它時,名為“fun”的function以毫秒為單位重復執行。
但是除了按住按鈕之外,我還想添加一個條件。 (就像“a == true”)
當我寫代碼時
if ( a == true ) { button.setOnTouchListener(RepeatListener(initialInterval, normalInterval, View.OnClickListener {
fun()
}))
這是我在這個網站上找到的 RepeatListener。
import android.os.Handler
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
/**
* A class, that can be used as a TouchListener on any view (e.g. a Button).
* It cyclically runs a clickListener, emulating keyboard-like behaviour. First
* click is fired immediately, next one after the initialInterval, and subsequent
* ones after the normalInterval.
*
*
* Interval is scheduled after the onClick completes, so it has to run fast.
* If it runs slow, it does not generate skipped onClicks. Can be rewritten to
* achieve this.
*/
class RepeatListener(initialInterval: Long, normalInterval: Long, clickListener: View.OnClickListener?) : OnTouchListener {
private val handler = Handler()
private val initialInterval: Long
private val normalInterval: Long
private val clickListener: View.OnClickListener
private var touchedView: View? = null
private val handlerRunnable: Runnable = object : Runnable {
override fun run() {
if (touchedView!!.isEnabled) {
handler.postDelayed(this, normalInterval)
clickListener!!.onClick(touchedView)
} else {
// if the view was disabled by the clickListener, remove the callback
handler.removeCallbacks(this)
touchedView!!.isPressed = false
touchedView = null
}
}
}
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
handler.removeCallbacks(handlerRunnable)
handler.postDelayed(handlerRunnable, initialInterval)
touchedView = view
touchedView!!.isPressed = true
clickListener.onClick(view)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(handlerRunnable)
touchedView!!.isPressed = false
touchedView = null
return true
}
}
return false
}
/**
* @param initialInterval The interval after first click event
* @param normalInterval The interval after second and subsequent click
* events
* @param clickListener The OnClickListener, that will be called
* periodically
*/
init {
requireNotNull(clickListener) { "null runnable" }
require(!(initialInterval < 0 || normalInterval < 0)) { "negative interval" }
this.initialInterval = initialInterval
this.normalInterval = normalInterval
this.clickListener = clickListener
}
}
它沒有正常工作..
如何寫“當 a 為真時,按住按鈕重復執行 fun()”?
寫類似的東西有什么問題
button.setOnTouchListener { if (a) fun() }
如果你想實現行為,比如“當a
為false
時,執行一次fun
,你也可以嘗試添加
button.setOnClickListener { if (a) return else fun() }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.