Issue
Intro
I'm new to Jetpack Compose and it is not that easy for me to understand or get everything correct on my first try.
That's why I love to have a look at other's open-source work to understand the topic a little bit better.
Problem
My current problem is that I must embed YouTube videos into my app. At first, I thought I use an embedded web view, but hey, I'm a native app dev, let's do it native!
But I stumbled a lot
- Is it true, that we as devs must use a local *.jar file from Google to embed the video player?
- Is it true, that there is no official Jetpack Compose component for that?
- Is it true, that there is no dependency our there which provides such functionality?
- Yes, I searched SO before I asked
That's why it would be awesome if someone of you could point me into the correct direction to make any progress with my tiny self-learning app.
Solution
Here are the answers:
As the official page says, yes you have to download a JAR.
Yes and it's not necessary. You can use
AndroidView
composable function to wrap aYouTubePlayerFragment
and play a video.But here you need to do a small-hack because the
YouTubePlayerFragment
does not extends fromandroidx.fragment.app.Fragment
. Therefore, you'll need the following:2.1 Create an implementation of
YoutubePlayerFragment
which usesandroidx
. You can copy from this gist.2.2 Then, you can use it in your composable...
@Composable
fun YoutubeScreen() {
val ctx = LocalContext.current
AndroidView(factory = {
val fm = (ctx as AppCompatActivity).supportFragmentManager
val view = FragmentContainerView(it).apply {
id = R.id.fragment_container_view_tag
}
val fragment = YouTubePlayerSupportFragmentXKt().apply {
initialize("YoutubeApiKey",
object : YouTubePlayer.OnInitializedListener {
override fun onInitializationFailure(
provider: YouTubePlayer.Provider,
result: YouTubeInitializationResult
) {
Toast.makeText(
context,
"Error playing video",
Toast.LENGTH_SHORT
).show()
}
override fun onInitializationSuccess(
provider: YouTubePlayer.Provider,
player: YouTubePlayer,
wasRestored: Boolean
) {
if (!wasRestored) {
player.cueVideo("YoutubeVideoId")
}
}
})
}
fm.commit {
setReorderingAllowed(true)
add(R.id.fragment_container_view_tag, fragment)
}
view
})
}
For the commit
function above, you will need this dependency:
implementation "androidx.fragment:fragment-ktx:$fragment_ktx_version"
Then add this in your AndroidManifest.xml
<queries>
<intent>
<action android:name="com.google.android.youtube.api.service.START" />
</intent>
</queries>
I tested the code above and it worked, but maybe you need some more working to handle orientation changes.
AFAIK and I mentioned in #1, no, there is not.
It's not a question :)
Answered By - nglauber
Answer Checked By - Terry (JavaFixing Volunteer)