美文网首页
Kotlin 自动获取ID

Kotlin 自动获取ID

作者: 小小的coder | 来源:发表于2020-06-09 00:00 被阅读0次

    像 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:0.8.3@aar'
    }

    详细文档:传送门

    总结:一 : 在1,2,3步骤中,缺一不可,必须全部添加,

    二 : 在使用Kotlin的 过程中,我发现代码上边的简洁很多,并且减少了不少的代码.但是刚接触这个的时候,很多规则不熟悉,查找资料起来,也不像Java那样充足,
    ————————————————
    原文链接:https://blog.csdn.net/LMH820822/java/article/details/76882472

    相关文章

      网友评论

          本文标题:Kotlin 自动获取ID

          本文链接:https://www.haomeiwen.com/subject/xpdjtktx.html