自升级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
}
}
答案 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
}