像 butterknife 或者DataBinding 同样,老是能够帮助咱们节约时间去findViewByID, 在Kotlin中,也能够这样,咱们只须要在XML布局中,将控件ID命名,而后就能够直接掉用了,具体实现以下:java
1 在项目的build.gradle中添加android
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中添加以下代码app
apply plugin: 'kotlin-android-extensions'//启用扩展支持直接使用ID
import kotlinx.android.synthetic.main.(xml.文件名).*
4 一下是个人xml文件部分代码,只须要注意控件ID便可.ide
<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"/>
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:0.8.3@aar' }
总结:一 : 在1,2,3步骤中,缺一不可,必须所有添加,gradle
二 : 在使用Kotlin的 过程当中,我发现代码上边的简洁不少,而且减小了很多的代码.可是刚接触这个的时候,不少规则不熟悉,查找资料起来,也不像Java那样充足,ui