android - Kotlin:不能将null强制转换为非null类型com.google.android.youtube.player.YouTubePlayerFragment-LMLPHP
我在我的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

08-03 22:28