[英]Binding views in android using kotlin
以下兩種使用kotlin在android中綁定視圖的方式有何區別?哪種更好?
TextView tvSelectDistance=findViewById<View>(R.id.tvSelectDistance) as TextView
VS
TextView tvSelectDistance=findViewById<TextView>(R.id.tvSelectDistance)
您應該使用android kotlin ktx插件來簡化此操作。 將此添加到您的build.gradle: apply plugin: 'kotlin-android-extensions'
當您將使用此插件時,無需自己查找視圖,只需執行以下操作:
// Instead of findViewById<TextView>(R.id.textView)
textView.setText("Hello, world!")
有關更多信息,請訪問此URL
您的問題:
在Android中, findViewById
返回一個View
我們需要將其顯式轉換為正確的類型(您正在使用第一種方法來執行此操作)。
在第二種方法中,您提供了一個TextView到findViewById的類型,因此無需進行類型轉換。
在舊版Android中,將 findViewById()
定義為
public View findViewById(@IdRes int id)
因此有必要將其轉換為正確的類型。
在當前版本中,其定義為
public <T extends View> T findViewById(@IdRes int id)
它只是通過調用隱式轉換發現的視圖。
因此,以下選項
TextView tvSelectDistance = findViewById<View>(R.id.tvSelectDistance) as TextView
TextView tvSelectDistance = findViewById<TextView>(R.id.tvSelectDistance)
TextView tvSelectDistance = findViewById(R.id.tvSelectDistance)
在技術上是等效的。 但是,您可以使用后兩個代碼,並使用一些更整潔的代碼,而不是顯式強制轉換返回值。
這應該是正確的方法:
val selectDistanceText: TextView = findViewById(R.id.tvSelectDistance)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.