Kotlinを使用する利点の1つは、Nullの安全性です。しかし、私はそれを使用してAndroidアプリケーションをプログラミングしているとき、私はnullを使用する必要が自分自身を発見した。 TextViewsやButtonsなどのUI要素を宣言するときは、onCreate中に各オブジェクトに初期化されるプライベート変数を作成する必要がありますが、これは各参照でnullを明示的に許可する必要があることを意味します。この種のものはKotlinを使う目的の一つを破るものです。 Androidでのアクティビティ内でUIオブジェクトのインスタンスを作成する方が、優れたソリューションがありますか?Nullの使用を避けるためのアクティビティ内のオブジェクトの管理
これは私が今やっていることです。
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)
}
なぜfindViewByIdを削除するためにKotlin Android Extensionsを使用しないのですか? –
私はAndroidの拡張機能に気づいていません。私は見てみましょう。 – xiimoss