Ni ck
Ni ck

Reputation: 21

Android studio - how to use long click on a button

I have a Button and when I click it it plays a Sound. How to use longpress to turn sound ( on and off ), so basically first tap should play a sound, second tap should stop it.

MainActivity

Upvotes: 2

Views: 605

Answers (2)

Amir Hedieh
Amir Hedieh

Reputation: 1178

You can use onLongClickListener:

Button button;
button = findViewById(R.id.<your_button_id>);
button.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        //your code goes here
        return false;
    }
});

Upvotes: 1

Gal
Gal

Reputation: 422

You have to add onLongClickListener to your button and implement the method onLongClick in your main activity. for example:

public class MainActivity implements View.OnLongClickListener

after you implement the onLongClickListener you override the function onLongCLick

 @Override
public boolean onLongClick(View view) {
    return false;
}

And finally you need to set onLongClickListener to your button

        btn.setOnLongClickListener(this);

In order to make the sound on and of just hold a global boolean variable which is called private boolean isPlaying;

When it is long pressed once you set it to true, and when it is called again set it to false.

and stop your sound.

Upvotes: 0

Related Questions