使用Kotlin Android Extensions代替ButterKnife和findViewById
簡要介紹
安卓開發中,activity獲取xml檔案中控制元件,最開始的方法是findViewById,後來出現了ButterKnife,於是很多專案都改用ButterKnife了.但是隨著Kotlin Android Extensions的推出,有更簡單的玩法了.
使用方法
- app工程頂部新增
apply plugin: 'kotlin-android-extensions'
如果工程本身不是Kotlin工程,則需新增kotlin支援,參考《 Android非Kotlin增加Kotlin支援方法 》 - 使用樣例
textView為activity_main.xml中定義的TextView的id,直接用,上面的import語句,IDE會自動匯入進來.
import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.text = "hello" } }
簡不簡單? 用過這個之後,你還會想ButterKnife麼?
安卓開發技術分享: https://www.jianshu.com/p/442339952f26
更多技術總結好文,請關注:「程式園中猿」
