In Android, VideoView is used to load video files. We can rely on any of the external resources, URLs, or the local data in order to fetch the video content. In this article, we will be discussing how to create a VideoView in Kotlin dynamically.
Note: If we use the video view in the background or just go back from a current video session, the old video position is not saved, that is the old state where we last left the video is not saved. In order to achieve it, we need to make use of some external databases to store the states.
Following methods are provided by the video view class in order to facilitate the whole procedure:
|public void start()||It is used to start the VideoView|
|public void pause()||Pauses the video|
|public void resume()||Resumes the video|
|public void stopPlayback()||Stops the video|
|public void setVideoURI (Uri uri)||It is used to set the path of the Video file which needs to be accesed. It can be a url, or a local path|
|public void seekTo(int millis)||Jumps to a specific interval of time|
|public void setMediaController(MediaController controller)||This is use to set the controllers of the VideoView (play, pause, fast forward like buttons which you see along the video)|
|public void getDuration()||It is used to get the total duration of the video|
|public void getCurrentPosition()||It is used to get the current time interval or position of the video|
|public void isPlaying()||It return a boolean value in accordance to whether the video is playing or not|
|public void setOnPreparedListener(MediaPlayer.OnPreparedListener)||It is a listener which acts when the video is just ready to start|
|public void setOnErrorListener(MediaPlayer.OnErrorListener)||It is a listener which acts when an error occurs while playing the video|
|public void setOnCompletionListener(MediaPlayer.OnCompletionListener)||It is a listener which acts when the video is completed|
|public void setAnchorView(View view)||It sets the position of the controls of media controller on the screen|
Create a new Project in Android Studio
To create a new project in Android Studuio follow these steps:
- Click on File, then New and then New Project and give name whatever you like.
- Choose “Empty Activity” for the project template.
- Then, select Kotlin language Support and click next button.
- Select minimum SDK, whatever you need
This is how your project directory should look like:
Modify activity_main.xml file
Now, we need to add the video. To do that, we have two options:
- We can have a video file stored locally on our system:
Create a folder named “Raw” in the res folder. Add the video file in it and use the following code snippet.
// val path = "android.resource://" + packageName + "/" + R.raw.your_videoFile_name // videoView.setVideoURI(Uri.parse(path))
- We can use the video file from any web resource:
// Uri uri = Uri.parse("your_custom_URL"); // videoView.setVideoURI(uri)
Create VideoView in MainActivity.kt file
Insert following code in your