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"/>

var btn_submit = findViewById(R.id.button_submit) as Button

或是:
private lateinit var textView : TextView

//in onCreate()
textView = findViewById(R.id.textView)

這樣的宣告才可使用,否則未宣告就使用會導致直接app crash.

若是有超過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
    }
}


In your class add import for import kotlinx.android.synthetic.main.<layout>.* where <layout> is the filename of your layout.
That's it, you can call any view item id in layout directly in your code.


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) 要更改成這.






留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

SMR疊瓦式hdd致命缺陷被解決????!!!

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

ios app 上架時app icon要注意事項

Gmail 永久刪除大型電子郵件

舊有app在Android 12 閃退問題& app Splash screens

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

google play 正式發布前測試報告...非常好用.