类型不匹配:推断的类型为Fragment,但应使用YouTubePlayerSupportFragment

时间:2019-06-16 09:14:57

标签: android kotlin youtube-api

自升级Android Studio以来,我一直收到此错误。 这是我的activity_main.xml(相关部分)

<fragment
            android:id="@+id/youtube_player_fragment"
            android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

这是我的MainActivity.kt

lass MainActivity : AppCompatActivity()
{
    lateinit var youTubePlayerSupportFragment: YouTubePlayerSupportFragment
    lateinit var youTubePlayer: YouTubePlayer


    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initializeYoutubePlayer()
    }


    private fun initializeYoutubePlayer()
    {
        youTubePlayerSupportFragment = supportFragmentManager.findFragmentById(R.id.youtube_player_fragment) //<-- I get ERROR in this line

    }
}

1 个答案:

答案 0 :(得分:1)

设置as时可以使用强制转换运算符youTubePlayerSupportFragment。默认情况下,findFragmentById返回Fragment类型的对象:

...
private fun initializeYoutubePlayer() {
    youTubePlayerSupportFragment = supportFragmentManager.findFragmentById(R.id.youtube_player_fragment) as YouTubePlayerSupportFragment
}
...

一个更简单的选择是直接使用其Fragment的ID,因为它已经在xml文件中定义了:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    //your Fragment is bound at this point
    assert youtube_player_fragment != null
}