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 a YouTubePlayerFragment
and play a video.
But here you need to do a small-hack because the YouTubePlayerFragment
does not extends from androidx.fragment.app.Fragment
. Therefore, you'll need the following:
2.1 Create an implementation of YoutubePlayerFragment
which uses androidx
. 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 :)