findViewById()
searches the current layout for the view and throws an exception if it isn't found. But there is no current layout yet at the time the Activity class is instantiated. There is only a layout after you have called setContentView()
in the onCreate()
function. Your tvInput
property in your example is calling findViewById()
at the time the class is instantiated.
If you want to delay when it first calls findViewById()
, you can use a Lazy delegate like this, and it will resolve the issue:
val tvInput: TextView by lazy { findViewById(R.id.tvInput) }
Now it won't call findViewById()
until the first time you actually use the property, which will happen after you call setContentView()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…