【问题标题】:I declared the val here, so that i can use the val e11 in all the function but it get crashes and why?我在这里声明了 val,这样我就可以在所有函数中使用 val e11 但它会崩溃,为什么?
【发布时间】:2023-12-23 06:30:01
【问题描述】:

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

【问题讨论】:

  • 这是因为您试图在创建视图之前查找视图 ID。 //val e11=findViewById(R.id.e1)

标签: android android-studio kotlin declaration kotlin-android-extensions


【解决方案1】:

试试这个

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

【讨论】:

  • 我不是 100% 确定,但是 val 是否会失败,因为 e11 不应该是最终的并且是 var
  • @MarcelHofgesang 根本原因是 findViewById。如果您在视图创建/膨胀之前访问它,它将失败/崩溃。您可以对 e11 变量使用 lateinit 或惰性声明。在lateinit中,你必须在使用它之前进行初始化,在lazy中它会在第一次使用时初始化并记住它的值以供进一步使用。
  • 希望这可行....val e11 by lazy{ findViewById(R.id.e11)
【解决方案2】:

正如@Kishan Maurya 在 cmets 中所述,您正试图在您的 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
    
}

【讨论】: