To play videos in an Android application using the VideoView
component, you can follow these steps:
- Add a
VideoView
to your layout XML file (activity_main.xml
):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<!-- Add this VideoView in your layout file -->
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.kt
package com.androindian.videoview
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.MediaController
import android.widget.VideoView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var videoUri: Uri? = null
private val pickVideoLauncher: ActivityResultLauncher<Intent> =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val data: Intent? = result.data
data?.data?.let {
videoUri = it
playVideo()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val videoView: VideoView = findViewById(R.id.videoView)
// Assuming you have a button with the ID "selectVideoButton" in your layout
// selectVideoButton.setOnClickListener {
openGalleryForVideo()
// }
}
private fun openGalleryForVideo() {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
pickVideoLauncher.launch(intent)
}
private fun playVideo() {
videoUri?.let {
val videoView: VideoView = findViewById(R.id.videoView)
// Create MediaController
val mediaController = MediaController(this)
mediaController.setAnchorView(videoView)
// Set video URI and attach MediaController to VideoView
videoView.setMediaController(mediaController)
videoView.setVideoURI(it)
// Start playing the video
videoView.start()
}
}
}