我正在尝试制作我的项目,以便当选择其中一个单选按钮并按住一个按钮时,它会产生所选的声音。但是当我使用ACTION_DOWN函数时,不会产生噪音。任何帮助都会很棒
public boolean onTouch(View v, MotionEvent event) {
int frequency = Integer.parseInt(frequencyInput.getText().toString());
displayFrequency.setText(String.valueOf(frequency));
sineWave.setSine(frequency);
squareWave.setSquareWave(frequency);
sawWave.setSawWave(frequency);
boolean on = ((startStop.isPressed()) && sine.isChecked());
boolean sqOn = ((startStop.isPressed()) && square.isChecked());
boolean sawOn =((startStop.isPressed()) && saw.isChecked());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (on)
{
sineWave.start();
}
else if (sqOn)
{
squareWave.start();
}
else if (sawOn)
{
sawWave.start();
}
break;
case MotionEvent.ACTION_UP:
if (!on) {
sineWave.stop();
}
if (!sqOn) {
squareWave.stop();
}
if (!sawOn) {
sawWave.stop();
;
}
break;
}
答案 0 :(得分:2)
主要问题是当你还在isPressed()
时检查onTouch
,因此按钮的按下状态尚未设置。
如果您将onTouchListener
直接添加到startStop按钮,则可以确保每次调用它时都会触发该事件的startStop按钮。这允许您删除startStop.isPressed()
支票。
startStop.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int frequency = Integer.parseInt(frequencyInput.getText().toString());
displayFrequency.setText(String.valueOf(frequency));
sineWave.setSine(frequency);
squareWave.setSquareWave(frequency);
sawWave.setSawWave(frequency);
boolean on = sine.isChecked();
boolean sqOn = square.isChecked();
boolean sawOn = saw.isChecked();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (on) {
sineWave.start();
} else if (sqOn) {
squareWave.start();
} else if (sawOn) {
sawWave.start();
}
break;
case MotionEvent.ACTION_UP:
if (!on) {
sineWave.stop();
}
if (!sqOn) {
squareWave.stop();
}
if (!sawOn) {
sawWave.stop();
}
break;
default:
return false;
}
return true;
}
});