管理活动中的对象以避免使用Null

时间:2017-10-27 14:18:04

标签: android kotlin

使用Kotlin的一个好处是它的Null安全性。然而,当我使用它编写Android应用程序时,我发现自己需要使用null。在声明我的UI元素(如TextViews和Buttons等)时,我需要创建在onCreate期间初始化为每个对象的私有变量,但这意味着我需要在每个引用上显式允许null。这种方式违背了使用Kotlin的目的之一。有没有更好的解决方案,在我的Android活动中创建UI对象的实例。

这就是我现在这样做的方式。

    var messageView: TextView? = null
    var firstNameView: EditText? = null
    var lastNameView: EditText? = null
    var ageView: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        messageView = findViewById<TextView>(R.id.message)
        firstNameView = findViewById<EditText>(R.id.firstName)
        lastNameView = findViewById<EditText>(R.id.lastName)
        ageView = findViewById<EditText>(R.id.age)

        findViewById<Button>(R.id.showMessage).setOnClickListener(this)
        findViewById<Button>(R.id.update).setOnClickListener(this)
    }

1 个答案:

答案 0 :(得分:3)

尝试将这些定义为lateinit,如果您可以保证在阅读之前提供值,那么它应该让您超过让它们为空的需要。

lateinit var messageView: TextView
lateinit var firstNameView: EditText
lateinit var lastNameView: EditText
lateinit var ageView: EditText

来自documentation for lateinit

  

通常,声明为具有非null类型的属性必须在构造函数中初始化。但是,这通常不方便。例如,可以通过依赖注入或单元测试的设置方法初始化属性。在这种情况下,您不能在构造函数中提供非null初始值设定项,但是在引用类体内的属性时仍然希望避免空值检查。