我在这里声明了val,这样我就可以在所有的函数中使用val e11,但它会崩溃,为什么?



怎么做?我在这里声明了val,这样我就可以在所有的函数中使用val e11但是它会崩溃,为什么?

//val e11=findViewById<EditText>(R.id.e1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lifecycle)
val b11=findViewById<Button>(R.id.b1)
b11.setOnClickListener{
startActivity(Intent(this,another::class.java))
}}
override fun onStart() {
super.onStart()
Toast.makeText(this, "am started", Toast.LENGTH_SHORT).show()
}override fun onResume() {
super.onResume()
Toast.makeText(this, "am resumed", Toast.LENGTH_SHORT).show()
}
override fun onPause() {
super.onPause()
val e1=findViewById<EditText>(R.id.e1)
e1.setText("")
}
}```

试试这个

private val e11 : EditText by lazy { findViewById<EditText>(R.id.e1) }

正如@Kishan Maurya在评论中指出的那样,您试图在onCreate函数中创建视图之前找到视图。一个解决方案可能是全局声明e11,并在您的onCreate中初始化它,就像它是最常见的一样。或者你试试@Kishan Maurya的答案。

lateinit var e11 : EditText // declare var e11 globally
// lateint is a keyword to tell that this var will be initialized later
// you need a var instead of val, because e11 should not be final
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
e11 = findViewById<EditText>(R.id.e11)
// you could also initialize like below; is simple and has better readability
// e11 = findViewById(R.id.e11) as EditText

}

最新更新