為什麼 Android Synthetics Deprecated

Chris Evans
codecodecode
Published in
3 min readAug 24, 2021

之前打算升級 Kotlin 到最新版本發現 Kotlin 在1.4.20開始,將 synthetic view 給 deprecated 了看官方說明,是希望大家使用 Jetpack 的 view binding ,有在使用 Kotlin synthetic view 開發 Android 可以注意一下,避免再更之後升級 Kotlin 時,需要改很多程式碼。

Recently Android has announced that with Kotlin 1.4.20, their Android Kotlin Extensions Gradle plugin will be deprecated and will no longer be shipped in the future Kotlin releases.

接著問題就是 “為什麼 kotlin synthetics 要 deprecated”,此外,deprecated 之後,那還有什麼選擇呢?

先重溫關於 Synthetics,

Android Kotlin Extensions plugin brought with it two very cool features

Synthetics let you replace calls to findViewById with kotlinx.android.synthetic bindings.

Parcelize allows you to remove boilerplate and easily create Parcelables through the @Parcelize annotation.

那麼帶來哪些好處和壞處呢?

首先,優點的話,

便利性,如果要使用的話,只需要在 gradle 加上設定

Type Safe,因為會直接參考到 layout 本身,所以就沒有需要考慮定義型別的問題

那麼,缺點呢?

只支援 kotlin,如果專案中還有java,就無法使用

Global Name Space,這會導致每個元件的命名都需要唯一

無法知道元件是否為空,就需要再多判斷

如果 Synthetics 被廢棄的話,那麼還有什麼選擇呢?

目前的話,可以選擇 Data Binding 以及 View Binding,Android 官方近期的專案大部分都是以 View Binding 為首選,而且如果以好上手和好除錯的情況下,更推薦選擇 View Binding。

View Binding 的優點如下,

  1. Null Safety
  2. Type Safety
  3. 沒有重複或是額外定義的程式碼,畢竟元件的定義都是 IDE 根據 Layout 生成的
  4. 相較於 Data Binding, Build Time 會少很多
  5. 如果還有 Legacy 的專案,同時有支援 Java 和 Kotlin

總結來說,從今天起就不要再用 Kotlin Synthetics,嘗試用用看 View Binding吧。

--

--