compsciman
compsciman

Reputation: 379

How to add tap to play/pause to a VideoView?

I'm trying to add video play/pause functionality into a chat that I'm making, so I have a standard:

VideoView vidRight;
vidRight = v.findViewById(R.id.videoViewRight);

However, trying to add a tap to play/pause with a listener is not possible as I would need to declare paused final:

boolean paused = false;
vidRight.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (paused) {
            vidRight.start();
            paused = false;
        }
        else {
            vidRight.stopPlayback();
            paused = true;
        }

        return true;
    }
});

Is there another way to do this?

Upvotes: 3

Views: 2578

Answers (3)

Giovanny Piñeros
Giovanny Piñeros

Reputation: 583

I've manage to handle this by implementing this code:

 if (videoView.isPlaying()) {
        videoView.pause();
     } else {
        videoView.start();         
     }

I hope this will be usefull for someone.

Upvotes: 0

Adarsh Yashvanth
Adarsh Yashvanth

Reputation: 150

You don't have to maintain a custom flag paused for checking the state. Instead you can use isPlaying to check if the video is currently playing or not.

vidRight.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (vidRight.isPlaying()) {
            vidRight.stopPlayback();
         }
         else {
            vidRight.start();
         }

         return true;
    }
});

Upvotes: 4

Gratien Asimbahwe
Gratien Asimbahwe

Reputation: 1614

Declare the "paused" variable as a member variable just like this:

public class YourClassName extends AppCompatActivity implements YourInterfaces {
    private boolean paused=false;
    /* your other variables */
      @Override
    public void onCreate(Bundle savedInstanceState) {

        vidRight.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    if (paused) {
                        vidRight.start();
                        paused = false;
                    }
                    else {
                        vidRight.stopPlayback();
                        paused = true;
                    }

                    return true;
                }
            });

Upvotes: 3

Related Questions