gpt4 book ai didi

android - Kotlin:不能将null强制转换为非null类型com.google.android.youtube.player.YouTubePlayerFragment

转载 作者:行者123 更新时间:2023-12-03 06:06:22 29 4
gpt4 key购买 nike

code pic
我在我的android项目中实现TouTube Api。我在YouTubePlayerFragment之前的“as”下一行出现错误,“此转换无法成功”。我正在用片段初始化youtube播放器。我已经在gradle.properties中尝试了android.enableJetifier = true,但它没有帮助

val youTubePlayerFragment = fragmentManager?.findFragmentById(R.id.vidVieW) as YouTubePlayerFragment
youTubePlayerFragment?.initialize(Config.getYoutubeApiKey(),monInitializedListener)
这是monInitializedListener代码。当我在 Activity 中使用此功能时,效果很好
monInitializedListener = object: YouTubePlayer.OnInitializedListener {
override fun onInitializationSuccess(
provider: YouTubePlayer.Provider,
player: YouTubePlayer,
wasRestored: Boolean
) {


if (!wasRestored) {
mPlayer = player

}

// player.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL)
val mydef="BPGJUPcbQ58"
mPlayer?.loadVideo(mydef)

Toast.makeText(activity?.baseContext, "Fragment Visible", Toast.LENGTH_SHORT).show()
}

override fun onInitializationFailure(
p0: YouTubePlayer.Provider?,
p1: YouTubeInitializationResult?
) {
Toast.makeText(activity?.applicationContext, "onInitializationFailure()", Toast.LENGTH_LONG).show()
}

//
}
这是我的XML 内部的一个片段
<fragment

android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="@+id/vidVieW"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/orientation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"

/>
在logcat中,我收到此错误
kotlin.TypeCastException: null cannot be cast to non-null type com.google.android.youtube.player.YouTubePlayerFragment

最佳答案

Kotlin默认情况下不允许使用可为空的类型。此处的问题是片段管理器可以为null,因此如果整个表达式都为null,则将其强制转换为不可为空的YoutubePlayerFragment。简单地,解决方案是通过代替as YouTubePlayerFragment将强制转换的as YouTubePlayerFragment?更改为可为空的类型
我个人也建议您检查Kotlin Documentation on Null Safety

关于android - Kotlin:不能将null强制转换为非null类型com.google.android.youtube.player.YouTubePlayerFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63313450/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com