kotlin findViewById 为空,找不到View

前提:

val headerView: View = LayoutInflater.from(this).inflate(R.layout.common_header, null)

 

错误示例:

import kotlinx.android.synthetic.main.common_header.*错误引入

headerView.hintTextView.text = getHint()错误写法1

hintTextView.text = getHint()错误写法2

 

正确写法:

1,正确写法一,findviewById

val hintTextView: TextView = headerView.findViewById(R.id.hintTextView)

 

2,正确写法二,引入

import kotlinx.android.synthetic.main.common_header.View*,正确引入

headerView.hintTextView.text = getHint()

 

原因:headerView不是Activity里边的View,是你自己生成的一个View,所以需要引入这个layout布局文件中所有的View,用headerView去点,或者你用headerView去findViewById

 

版权声明:本文为Goals1989原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。