Kotlin: View Binding
最近工作有點不如意阿,壓力太大,總是遇到不好的人...
嘆~
Android app一般情況下的UI component :Button,textview...,使用前須透過 :
(最新方法:)developer - View Binding
https://developer.android.com/topic/libraries/view-binding
(舊式,已可以全部改用view binding.)
ButterKnife
https://github.com/JakeWharton/butterknife
(原始方法,若程式元件不多,可直接用這方法取得ui元件)
findViewById
https://developer.android.com/reference/android/view/View#findViewById(int)
< Button android: id= "@+id/button_submit" android: src= "@drawable/image1" android: layout_width= "wrap_content" android: layout_height= "wrap_content" />
或是: private lateinit var textView : TextView //in onCreate() textView = findViewById(R.id.textView)
|
若是有超過10個以上的UI元件,程式碼就變成非常繁瑣,有一大部分都在寫這重複的code,所以就有view-binding的出現.
(In most cases, view binding replaces
findViewById
.)----
View-Binding:
https://developer.android.com/topic/libraries/view-binding
you need to use the below in your app gradle:
android {
...
buildFeatures {
viewBinding true
}
}
private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
setContentView(binding.root)
}
增加上面這幾行,有了這幾行,就少了很大的一部分findViewById(...) Code.
程式碼變簡潔多了.
重點是 setContentView(binding.root) 要更改成這.
留言
張貼留言