片剂上的片段视图为空
我正在尝试从Android Developers网站获得的Fragment基础源代码。 我通过使用代码>转换为Kotlinfunction将代码转换为Kotlin,并尝试在Nexus 10 API 23仿真器平板电脑上运行。
我在这一行的ArticleFragment
中出现错误:
fun updateArticleView(position: Int) { //here, there is no view in activity for ID article, so it's null val article = activity.findViewById(R.id.article) as TextView article.text = Ipsum.Articles[position] mCurrentPosition = position }
错误是:
kotlin.TypeCastException: null cannot be cast to non-null type android.widget.TextView at com.example.fragmentbasics.ArticleFragment.updateArticleView(ArticleFragment.kt:45)
我试着调试它,当它应该是null时,活动中没有View。 我错过了什么?
您可以初始化片段中的视图为:
val article = view!!.findViewById(R.id.article) as TextView
视图是片段中的膨胀视图。