Skip to content
Related Articles

Related Articles

Dynamic VideoView in Kotlin
  • Last Updated : 18 Feb, 2021

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:

METHODDESCRIPTION
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:

  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 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)) 
    
  2. 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.




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 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

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :