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

Android 我在这里声明了val,因此我可以在所有函数中使用val e11,但它会崩溃,为什么?,android,android-studio,kotlin,declaration,kotlin-android-extensions,Android,Android Studio,Kotlin,Declaration,Kotlin Android Extensions,怎么办? 我在这里声明了val,因此我可以在所有函数中使用val e11,但它会崩溃,为什么 //val e11=findViewById<EditText>(R.id.e1) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lifecycle)

怎么办? 我在这里声明了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("")
    }
}```

//val e11=findviewbyd(R.id.e1)
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u生命周期)
val b11=findViewById(R.id.b1)
b11.setOnClickListener{
startActivity(Intent(这个,另一个::class.java))
}}
覆盖有趣的onStart(){
super.onStart()
Toast.makeText(这个“am start”,Toast.LENGTH\u SHORT.show()
}重写onResume(){
super.onResume()
Toast.makeText(这个“am恢复”,Toast.LENGTH\u SHORT.show()
}
覆盖暂停(){
super.onPause()
val e1=findViewById(R.id.e1)
e1.setText(“”)
}
}```
试试这个

private val e11 : EditText by lazy { findViewById<EditText>(R.id.e1) }
private val e11:lazy{findViewById(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
    
}
lateinit var e11:EditText//全局声明var e11
//lateint是一个关键字,用于告知稍后将初始化此变量
//您需要var而不是val,因为e11不应该是最终值
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
e11=findViewById(R.id.e11)
//您也可以像下面这样初始化;它很简单,可读性更好
//e11=作为编辑文本的findViewById(R.id.e11)
}

这是因为您试图在创建视图之前找到视图id//val e11=findViewById(R.id.e1)我不是100%确定,但可能是
val
会失败,因为e11不应该是最终的,而是
var
?@Marcelhoffesang根本原因是findViewById。如果在视图创建/膨胀之前访问它,它将失败/崩溃。您可以对e11变量使用lateinit或lazy声明。在lateinit中,您必须在使用它之前进行初始化,在lazy中,它将在第一次使用时进行初始化,并记住它的值以供进一步使用。希望这能起作用…val e11 by lazy{findViewById(R.id.e11)