Tru*_*los 8 android button ontouchlistener touch-event
我正在使用特定的中间件(不重要)在Android中开发一个电视远程模拟器应用程序.
在音量按钮(音量+和音量 - )的情况下,我要做的是在按下按钮时重复发送"音量调高"信号.
这就是我最后尝试的(其中一个按钮的代码,另一个必须相同,除了名称):
声明了一个布尔变量
boolean pressedUp = false;
Run Code Online (Sandbox Code Playgroud)使用以下AsyncTask声明了一个内部类:
class SendVolumeUpTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
while(pressedUp) {
SendVolumeUpSignal();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
}
将侦听器添加到按钮:
final Button buttonVolumeUp = (Button) findViewById(R.id.volup);
buttonVolumeUp.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(pressedUp == false){
pressedUp = true;
new SendVolumeUpTask().execute();
}
case MotionEvent.ACTION_UP:
pressedUp = false;
}
return true;
}
});
Run Code Online (Sandbox Code Playgroud)我也尝试使用简单的线程,如在Increment-Decrement计数器中按下按钮但不起作用.该应用程序可以很好地用于其余按钮(通道等),但完全忽略了音量变化.
您忘记添加休息时间;在 MotionEvent.ACTION_DOWN: 情况的末尾。这意味着该行 pressUp = false; 即使在该操作上也会被执行。正确的做法是:
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(pressedUp == false){
pressedUp = true;
new SendVolumeUpTask().execute();
}
break;
case MotionEvent.ACTION_UP:
pressedUp = false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)