Kotlin 自动获取ID

在Kotlin中,可以通过特定方式自动获取XML布局的控件ID,类似于butterknife和DataBinding。需要在项目的build.gradle和app的build.gradle中添加配置,并确保XML控件ID命名正确。这种方法简化了代码,减少了findViewByID的操作,但在初期可能因规则不熟悉导致学习成本增加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

像 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那样充足,奋斗奋斗奋斗

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值