我希望我的应用能够识别何时同时按住两个按钮

时间:2019-08-15 15:28:24

标签: android button kotlin ontouchlistener

我只想在同时同时按住两个特定按钮的情况下在屏幕上显示活动。我正在使用onTouchListeners来检查它们是否被保留,并试图使用when语句来查看两者均成立,但是我没有看到when语句的输出。

var button1 = false
var button2 = false

buttonOne.setOnTouchListener { view, motionEvent ->
println("Button 1 is held!")
button1 = true
true
}
buttonTwo.setOnTouchListener { view, motionEvent ->
println("Button 2 is held!")
button2= true
true
}
when (button1 && button2) {
true -> println("Both buttons are held!")
}

我希望得到这样的结果:

I/System.out: Button 1 is held!
I/System.out: Button 2 is held!
I/System.out: Both buttons are held!

但只能得到:

I/System.out: Button 1 is held!
I/System.out: Button 2 is held!

2 个答案:

答案 0 :(得分:0)

Android并非如此。当您第一次触摸视图时,该视图将拥有所有触摸事件,直到发生两件事之一-您松开所有手指或父母窃取了该事件。它不会将某些触摸事件发送到一个视图,而将某些事件发送到另一个视图。如果要执行此操作,则触摸处理程序将需要能够分辨出另一只手指何时在另一视图中。

您将不得不编写一个复杂得多的触摸处理程序,以查找多点触摸事件,并进行测试以决定何时触摸两个视图。

答案 1 :(得分:0)

两个按钮都可以使用TouchListener。

https://developer.android.com/reference/android/view/View.OnTouchListener

然后,您可以观看特定事件MotionEvents。

https://developer.android.com/reference/android/view/MotionEvent.html

您将对ACTION_DOWN MotionEvent最感兴趣。

如果您基于此事件设置标志并测试是否存在相反的button_down标志,那么您应该能够知道何时按下这两个标志。

var button1 = false
var button2 = false

buttonOne.setOnTouchListener { view, motionEvent ->
  when (motionEvent) {
    ACTION_DOWN -> button1 = true; checkButtons()
    ACTION_CANCEL -> button1 = false
  }
  true
}

buttonTwo.setOnTouchListener { view, motionEvent ->
  when (motionEvent) {
    ACTION_DOWN -> button2 = true; checkButtons()
    ACTION_CANCEL -> button2 = false
  }
  true
}

fun checkButtons {
  if (button1 && button2) {
    println("Both buttons are held!")
  }
}