Open In App

Dynamic VideoView in Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

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:

METHOD DESCRIPTION
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 accessed. 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 Studio follow these steps:

  1. Click on File, then New and then New Project and give name whatever you like.
  2. Choose “Empty Activity” for the project template.
  3. Then, select Kotlin language Support and click next button.
  4. Select minimum SDK, whatever you need

This is how your project directory should look like: android-project-directory

Modify activity_main.xml file

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
</LinearLayout>


Add Video

Now, we need to add the video. To do that, we have two options:

  1. 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)) 
  1. 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 MainActivity.kt

Java




package gfg.apps.videoview
 
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.*
 
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // creating a VideoView
        val videoView = VideoView(this)
 
        // setting height and width of the VideoView in our linear layout
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        layoutParams.setMargins(10, 10, 10, 10)
        videoView.layoutParams = layoutParams
 
        // accessing the media controller
        val mediaController = MediaController(this)
        mediaController.setAnchorView(videoView)
        videoView.setMediaController(mediaController)
 
        // setting the video access path
        val path = "android.resource://" + packageName + "/" + R.raw.gfg
        videoView.setVideoURI(Uri.parse(path))
 
        val linearLayout = findViewById<LinearLayout>(R.id.layout)
        // Add VideoView to LinearLayout
        linearLayout?.addView(videoView)
    }
}


AndroidManifest.xml file

XML




<?xml version="1.0" encoding="utf-8"?>
    package="gfg.apps.videoview">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>


Run on Emulator



Last Updated : 25 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads