I'm researching for one day but didn't get any reference about youtube API with jetpack compose. is it possible to use it on jetpack compose or is there any other way to play youtube videos with jetpack compose? Please Help me
Indeed, tricky one.
You cannot use YouTubeBaseActivity, means you cannot use YouTubePlayerView. This view created to work ONLY inside one activity type and does not created for your fragment/compose architecture.
You cannot use YouTubePlayerFragment, because its parent origin from android.app package, which is deprecated, you will not be able to get old fragmentManager inside your fancy compose activity.
You can and MUST use YouTubePlayerSupportFragment with compose activity fragment manager(which is instance of androidx.fragment.app.FragmentManager).
Following code works fine on my side, try it out:
@Composable
fun ComposeYoutube(
modifier: Modifier,
playList: List<String>,
supportFragmentManager: FragmentManager,
onError: (String) -> Unit
) {
AndroidView(
modifier = modifier,
factory = {
var player: YouTubePlayer? = null
val onPlaylistChangeListener = object : YouTubePlayer.PlaylistEventListener {
override fun onPlaylistEnded() {}
override fun onPrevious() {}
override fun onNext() {}
}
val youtubeApiInitializedListener = object : YouTubePlayer.OnInitializedListener {
override fun onInitializationSuccess(p0: YouTubePlayer.Provider?, p1: YouTubePlayer?, p2: Boolean) {
player = p1
player?.setPlaylistEventListener(onPlaylistChangeListener)
player?.loadVideos(playList)
}
override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {
onError("TODO")
}
}
FrameLayout(it).apply {
// select any R.id.X from your project, it does not matter what it is, but container must have one for transaction below.
id = R.id.tv_id
val youtubeView = YouTubePlayerSupportFragment()
supportFragmentManager
.beginTransaction()
.add(
R.id.tv_id,
youtubeView,
null
)
.commit()
youtubeView.initialize(BuildConfig.youtubeApi, youtubeApiInitializedListener)
}
},
update = { }
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With