0

I’m new one here and I’m kind of a new one in java. All my knowledge about code based on what I can find in web for my project. So in one hand I know some difficult stuff on the other hand I don’t know a simple things. Right now I’m stuck in this situation.

I have button with looped sound what I’m trying to do is when i touch button it should change image on "button_prees" when i release button it should play sound and change image on "button_on" So for that moment code below work fine but now I’m trying to do reverse sequence. You touch the same button and it change image on "button_prees2" than when you release button it should stop playing sound and change image on "button_off"

How implement this in code below ?

final Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:


                       b1.setBackgroundResource(R.drawable.button_prees);

                        break;

                    case MotionEvent.ACTION_MOVE:

                        break;

                    case MotionEvent.ACTION_UP:


                        myS.play(s1I, 1, 1, 1, -1, 1);

                        b1.setBackgroundResource(R.drawable.button_on);

                        break;
                }
                return true;
            }
        });

1 Answers1

0

You could use a boolean as a flag for the Button state. Very briefly and basically:

boolean soundsOn = false;
public void setSoundsOn(boolean soundsOn){
    this.soundsOn = soundsOn;
}

public boolean isSoundsOn(){
    return soundsOn;
}
...

// Then for your Button listener:
onTouch(...)
if (!isSoundsOn){
  // Your above above code to change resources, start playing
  // EXCEPT 
  case MotionEvent.ACTION_UP: 
  ...
  setSoundsOn(true);
  ...
}else{
  // Code to stop etc.
  // INCLUDING 
  case MotionEvent.ACTION_UP: 
  ...
  setSoundsOn(false);
  ...
}
...

Ideally you should make sure sound has successfully started/stopped before calling setSoundsOn(...) otherwise your labels might end up saying what is not. Hope this helps...