Event for VideoView playback state or MediaController play/pause

后端 未结 2 1078
粉色の甜心
粉色の甜心 2020-11-30 01:03

I cant seem to find an event that listens for playback state. I am mostly interested in the play/pause state. I am using MediaController which has

2条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 01:26

    If you're using the MediaController in combination with a VideoView, it should be relatively easy to extend the latter and add your own listener to it.

    The custom VideoView would then look something like this in its most basic form:

    public class CustomVideoView extends VideoView {
    
        private PlayPauseListener mListener;
    
        public CustomVideoView(Context context) {
            super(context);
        }
    
        public CustomVideoView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomVideoView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public void setPlayPauseListener(PlayPauseListener listener) {
            mListener = listener;
        }
    
        @Override
        public void pause() {
            super.pause();
            if (mListener != null) {
                mListener.onPause();
            }
        }
    
        @Override
        public void start() {
            super.start();
            if (mListener != null) {
                mListener.onPlay();
            }
        }
    
        public static interface PlayPauseListener {
            void onPlay();
            void onPause();
        }
    
    }
    

    Using it is identical to using a regular VideoView, with the only difference being that we can now hook up our own listener to it.

    // Some other code above...
    CustomVideoView cVideoView = (CustomVideoView) findViewById(R.id.custom_videoview);
    cVideoView.setPlayPauseListener(new CustomVideoView.PlayPauseListener() {
    
        @Override
        public void onPlay() {
            System.out.println("Play!");
        }
    
        @Override
        public void onPause() {
            System.out.println("Pause!");
        }
    });
    
    cVideoView.setMediaController(new MediaController(this));
    cVideoView.setVideoURI(...);
    // or
    cVideoView.setVideoPath(...);
    // Some other code below...
    

    Finally, you may also declare it in your xml layout and inflate it (as shown above) - just make sure your use .CustomVideoView. Example:

    
    

提交回复
热议问题