1. 程式人生 > >Kotlin 自動獲取ID

Kotlin 自動獲取ID

像 butterknife 或者DataBinding 一樣,總是可以幫助我們節約時間去findViewByID, 在Kotlin中,也可以這樣,我們只需要在XML佈局中,將控制元件ID命名,然後就可以直接掉用了,具體實現如下:

1 在專案的build.gradle中新增

buildscript {

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        //自動尋找ID
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}



2 做完第一步後,並不能自動尋找控制元件ID,還需要在app 的build.gradle中新增如下程式碼

apply plugin: 'kotlin-android-extensions'//啟用擴充套件支援直接使用ID


3 在引用佈局的類中,匯入對於的xml檔案索引, 列如我的xml檔案叫activity_main.xml, 匯入的程式碼為:import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.(xml.檔名).*

4 一下是我的xml檔案部分程式碼,只需要注意控制元件ID即可.

 <EditText
            android:id="@+id/mEtContent"
            android:layout_width="match_parent"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:textSize="18sp"
            android:maxLength="20"
            android:textColor="@color/gray"
            android:hint="請輸入"
            android:layout_height="wrap_content"/>

5 Kotlin中直接使用控制元件ID,即可直接通過ID即可呼叫對應的方法和屬性,並不需要在去findViewByID了.
 mEtContent.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                
            }

        })

6 向步驟5這樣,也需要我們也許只用到onTextChanged這一個方法,那麼其他的方法需要都要實現,程式碼有變多了,可以試試以下寫法:

mEtContent.textWatcher { onTextChanged { text, start, before, count -> mTvCount.text =""+ (count+start)+"/20" }}
程式碼是不是簡潔了很多大笑,具體配置如下:
repositories {
    jcenter()
}

dependencies {
    compile 'com.pawegio.kandroid:kandroid:[email protected]'
}

詳細文件:傳送門


總結:一 : 在1,2,3步驟中,缺一不可,必須全部新增,

二 : 在使用Kotlin的 過程中,我發現程式碼上邊的簡潔很多,並且減少了不少的程式碼.但是剛接觸這個的時候,很多規則不熟悉,查詢資料起來,也不像Java那樣充足,奮鬥奮鬥奮鬥