这是我的代码:
up.setOnClickListener{GlobalScope.launch{cor.TCP(toWrite="Up")}}
down.setOnClickListener{GlobalScope.launch{cor.TCP(toWrite="Down")}}
left.setOnClickListener{GlobalScope.launch{cor.TCP(toWrite="Left")}}
right.setOnClickListener{GlobalScope.launch{cor.TCP(toWrite="Right")}}
它将TCP请求发送到预定义的套接字和端口。有4个按钮:上,下,左和右。我想在按下按钮后发送命令,因为我正在使用它来控制机器人,所以当我发送“ Up”时,它会无限地向上移动,而当我停止按下按钮时,我想发送一个停止命令。那么,单击按钮后如何发送命令?非常感谢!
答案 0 :(得分:1)
如果我对您的理解很好,则应该改用OnTouchListener
。
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Button pressed - send whatever move command
case MotionEvent.ACTION_UP:
// Button unpressed - send STOP command
}
return true;
}
您可以使用View
来检测触摸了哪个按钮
答案 1 :(得分:1)
您可以尝试使用 View.onTouchListener 代替onClickListener。 OnTouchListener使您可以访问视图的MotionEvent,在这种情况下,您可能需要MotionEvent.ACTION_UP和MotionEvent.ACTION_DOWN,使用它们来过滤应触发的操作。
您始终可以参考文档:
答案 2 :(得分:1)
以下是@cesarmarch答案的科特林版本,可以更恰当地描述您的用例
首先
您的课程需要实现View.OnTouchListener
第二
您需要覆盖onTouch方法
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
when (view) {
up -> {
when (motionEvent.action){
MotionEvent.ACTION_DOWN -> {
GlobalScope.launch{cor.TCP(toWrite="Up")}
}
MotionEvent.ACTION_UP -> {
//... Stop the robot here
}
}
}
down -> {
when (motionEvent.action){
MotionEvent.ACTION_DOWN -> {
GlobalScope.launch{cor.TCP(toWrite="Down")}
}
MotionEvent.ACTION_UP -> {
//... Stop the robot here
}
}
}
left -> {
//... Do similar motion check as above
}
right -> {
//... Do similar motion check as above
}
}
return true
}
最后
在按钮上设置监听器
...
up.setOnTouchListener(this)
down.setOnTouchListener(this)
left.setOnTouchListener(this)
right.setOnTouchListener(this)
...
答案 3 :(得分:-1)
您无法在GlobalScope中停止协程。在您的班级中定义custom scope