问题
I'm currently trying to make my project so that when one of the radio buttons are selected and a button is held then it produces the selected sound. however when I used the ACTION_DOWN function, no noise is produced. Any help would be great
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;
}
回答1:
The main problem is that you check for isPressed()
while you are still in onTouch
, so the pressed state of the button has not been set yet.
If you add the onTouchListener
directly to the startStop button you can be sure that every time it is called it is the startStop button that triggered the event. This allows you to remove the startStop.isPressed()
check.
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;
}
});
来源:https://stackoverflow.com/questions/42531910/android-action-down-with-radio-button