說說在 Android 中如何不使用 findViewById() 來獲取資源對象

1 安裝

在 build.grade 中加入以下配置[1]

apply plugin: 'kotlin-android-extensions'

點擊 “Sync Now” 進行安裝:

2 使用

在 Activity 類中導入 import kotlinx.android.synthetic.main.first_layout.*

然後就可以直接使用資源 ID 來引用對象了:

資源 ID 是定義在 layout.xml 類型的文件中:

   <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按鈕" />

通過 kotlin-android-extensions 插件,簡化了 Android 代碼開發,推薦使用。

參考資料

  1. https://www.jianshu.com/p/8fa6854566e9

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章