Kotlin Android YouTubePlayerView Examples

Let us look at a Android YouTubePlayerView example.

What is YouTubePlayerView?

It is a library to play YouTube Videos.

Problem 1 - Jar File

  • We should use Jar library file, not like implementation xxxx
  • That is old way and it makes difficult to manage the library

Problem 2 - Fragment style

  • If you want YouTube player with another view, you have to use YouTubePlayerFragment (Or you have to extend YouTubeBaseActivity)

<FrameLayout
    android:id="@+id/youtube_player_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
val youtubePlayerFragment = YouTubePlayerSupportFragment()
fragmentManager.beginTransaction()
    .replace(binding.youtubePlayerContainer.id, youtubePlayerFragment)
    .commitAllowingStateLoss()
youtubePlayerFragment.initialize(...)

Problem 3 - Conflict Fragment with androidx

YouTubePlayerView is super easy YouTube Player View.

Step 1: Install it

Install it from Maven central:

Maven Central

dependencies {
    implementation 'kr.co.prnd:youtube-player-view:x.x.x'
    //implementation 'kr.co.prnd:youtube-player-view:1.3.0'    
}

Step 2: Add to Layout

  • You can use 2 style

XML style

 <kr.co.prnd.YouTubePlayerView
    android:id="@+id/you_tube_player_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:videoId="VIDEO_ID" />

Dynamic code style

<kr.co.prnd.YouTubePlayerView
    android:id="@+id/you_tube_player_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Step 3: Write Code

Invoke the play() function to play a YouTube video:

val youTubePlayerView:YouTubePlayerView = findViewById(R.id.you_tube_player_fragment_view)
youTubePlayerView.play(VIDEO_ID)

Fragment

  • If you want use this YouTubePlayerView in fragment, you have to use fragment attribute in xml
<kr.co.prnd.YouTubePlayerView
    android:id="@+id/you_tube_player_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:fragment="com.example.youtubeplayerview.Sample2Fragment" />
  • If you use Proguard, you have to add your fragment class name in your proguard-rules.pro file
-keepnames class com.example.youtubeplayerview.Sample2Fragment

FAQ

Why don't you need a developer key?

  • This is a very strange thing.
  • When we use youtube player api, you can use any developer key without empty string
  • So YouTubePlayerView set developer key itself
  • Check this code

Here is a full example:

Example 1: YouTubePlayerView-master

This example will comprise the following files:

  • MainActivity.kt
  • Sample1Activity.kt
  • Sample2Activity.kt
  • Sample2Fragment.kt

Step 1: Create Project

  1. Open your AndroidStudio IDE.
  2. Go to File-->New-->Project to create a new project.

Step 2: Add Dependencies

In your app/build.gradle add dependencies as shown below:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    defaultConfig {
        applicationId "com.example.youtubeplayerview"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':youtube-player-view')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation "com.google.android.material:material:1.2.0-alpha01"
}

Step 3: Design Layouts

*(a). activity_main.xml

Create a file named activity_main.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_sample1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity Style" />

    <Button
        android:id="@+id/btn_sample2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment Style" />
</LinearLayout>

*(b). activity_sample1.xml

Create a file named activity_sample1.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <kr.co.prnd.YouTubePlayerView
        android:id="@+id/you_tube_player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <!--

        <kr.co.prnd.YouTubePlayerView
            android:id="@+id/you_tube_player_fragment_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:videoId="m2SZ6RV_J7I" />
    -->

</LinearLayout>

*(c). activity_sample2.xml

Create a file named activity_sample2.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

*(d). fragment_sample1.xml

Create a file named fragment_sample1.xml and design it as follows:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <kr.co.prnd.YouTubePlayerView
        android:id="@+id/you_tube_player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:fragment="com.example.youtubeplayerview.Sample2Fragment" />
    <!--

        <kr.co.prnd.YouTubePlayerView
            android:id="@+id/you_tube_player_fragment_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:fragment="com.example.youtubeplayerview.Sample2Fragment"
            app:videoId="m2SZ6RV_J7I" />
    -->

</LinearLayout>

Step 4: Write Code

Write Code as follows:

(a). MainActivity.kt

Create a file named MainActivity.kt

This will start the activity that will play the youtube video in an activity

        findViewById<Button>(R.id.btn_sample1).setOnClickListener {
            startActivity(Intent(this, Sample1Activity::class.java))
        }

This will start the activity hosting Fragments that will play the youtube video

        findViewById<Button>(R.id.btn_sample2).setOnClickListener {
            startActivity(Intent(this, Sample2Activity::class.java))
        }

Here is the full code

package com.example.youtubeplayerview

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.btn_sample1).setOnClickListener {
            startActivity(Intent(this, Sample1Activity::class.java))
        }

        findViewById<Button>(R.id.btn_sample2).setOnClickListener {
            startActivity(Intent(this, Sample2Activity::class.java))
        }

    }

}

(b). Sample1Activity.kt

Create a file named Sample1Activity.kt

Reference the YouTubePlayerView and set its ID to the play() function

        val youTubePlayerView = findViewById<YouTubePlayerView>(R.id.you_tube_player_view)
        youTubePlayerView.play(VIDEO_ID)

Here is the full code

package com.example.youtubeplayerview

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kr.co.prnd.YouTubePlayerView

class Sample1Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample1)

        val youTubePlayerView = findViewById<YouTubePlayerView>(R.id.you_tube_player_view)
        youTubePlayerView.play(VIDEO_ID)
    }

    companion object {
        private const val VIDEO_ID = "m2SZ6RV_J7I"
    }

}

(c). Sample2Activity.kt

Create a file named Sample2Activity.kt

Here is the full code

package com.example.youtubeplayerview

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class Sample2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample2)
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, Sample2Fragment.newInstance())
                .commitNow()
        }
    }

}

(d). Sample2Fragment.kt

Create a file named Sample2Fragment.kt

This example looks at how to play the YouTube video in a Fragment. Override the onActivityCreated() then reference YouTubePlayerView and invoke its play() function, passing in the ID:


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val youTubePlayerView =
            view?.findViewById<YouTubePlayerView>(R.id.you_tube_player_view)
        youTubePlayerView?.play(VIDEO_ID)

    }

Here is the full code

package com.example.youtubeplayerview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kr.co.prnd.YouTubePlayerView

class Sample2Fragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = inflater.inflate(R.layout.fragment_sample1, container, false)

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val youTubePlayerView =
            view?.findViewById<YouTubePlayerView>(R.id.you_tube_player_view)
        youTubePlayerView?.play(VIDEO_ID)

    }

    companion object {
        fun newInstance() = Sample2Fragment()
        private const val VIDEO_ID = "m2SZ6RV_J7I"
    }
}

Run

Simply copy the source code into your Android Project,Build and Run.

Reference

  1. Download code or Browse here.
  2. Follow code author.