Native Mobile App Development With Java

Android VideoView

15-Sep-2024

How to use and implement VideoView widget to play video files in Android Studio Project Java

The VideoView is a widget provided by the Android framework for playing videos. Below is a simple example of how you can use VideoView in your Android application.



Here is the tutorial for Kotlin





There Are Some Common Attributes for VideoView :


id
This ID serves as the control's unique identity.
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size





Step 1:

First, make sure you have a video file in your res/raw directory. If not, you can create a raw directory under the res folder and add your video file there.






Step 2:


File open res/layout/activity_main.xml file −:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>


Step 3:

File open com.microappvalley.newtestproject/MainActivity.java file −

Java:

package com.microappvalley.newtestproject;


import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {


@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the VideoView in the layout
VideoView videoView = findViewById(R.id.videoView);

// Set the path of the video file
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.sample_video;

// Create a Uri object from the video path
Uri uri = Uri.parse(videoPath);

// Set up the MediaController to control playback
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);

// Set the Uri to the VideoView
videoView.setVideoURI(uri);

// Start playing the video
videoView.start();
}
}




Open Device Manager, run the emulator, and  then run the application. Next, check the working output and check the output  you declared in your code.


Output:





Comments