I wanted to implement Youtube Player in jetpack compose by
@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
})
}
I use Hilt and my Activity inherit ComponentActivit but AppCompatActivity is required in the example above.
MainActivity : ComponentActivity()
Link to tutorial: Looking for a Jetpack Compose YouTube Video Player wrapper dependency