Android VideoView Tutorial: Complete Guide

Android VideoView is a view control used for playing videos in Android applications, allowing for the display of videos and providing basic video playback functions such as play, pause, and stop.

The usage of VideoView is as follows:

  1. Add a VideoView control to the layout file.
<VideoView
    android:id="@+id/videoView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. Find the VideoView control in the Activity or Fragment and set the video source.
VideoView videoView = findViewById(R.id.videoView);
String videoUrl = "https://example.com/video.mp4";
videoView.setVideoURI(Uri.parse(videoUrl));
  1. You can control video playback by calling some methods of VideoView, such as:
  1. Play video:
videoView.start();
  1. Pause the video.
videoView.pause();
  1. Stop the video.
videoView.stopPlayback();
  1. Adjust video playback position:
int position = 10000; // 单位为毫秒
videoView.seekTo(position);
  1. Listen for the event when the video finishes playing.
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        // 视频播放完成后的处理逻辑
    }
});
  1. Listen for video playback error events.
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
        // 视频播放出错时的处理逻辑
        return false;
    }
});

It is important to note that VideoView only supports common video formats such as MP4 and 3GP. If you need to play other formats, consider using ExoPlayer or MediaPlayer. Additionally, for more advanced video playback functions, you can inherit VideoView or customize your own view.

bannerAds