Kotlin减少findViewById

在Kotlin出来前为了减少 findViewById的使用,用 Butterknife,但每次也需要定义注解,Kotlin出来后可以直接使用xml中定义的id

配置:在项目 build中

apply plugin: 'kotlin-android-extensions'
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}

仓库带上:

repositories {
    mavenCentral()
}

使用方式如下:

1、在Activity、fragment 中

直接使用 布局id,然后会自动导包,例如:

import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.android.synthetic.main.toolbar_main.*

这里要注意fragment中要在 onViewCreated 中使用id,不能在onCreateView 中使用。

2、在其他类里面使用,例如RecylceView的ViewHolder中,需要实现LayoutContainer 接口

class MealDateScanItemViewHolder2(view: View?) : BaseViewHolder(view) , LayoutContainer {
    private var containView =view

    override val containerView: View?
        get() = containView
}

原理:通过工具 Show Kotlin Bytecode可以看到

实际上调用了_$_findCachedViewById,这个就是类似java的findViewById,只不过这个方法中增加cache功能,会把之前找过的View用HashMap缓存起来。

猜你喜欢

转载自blog.csdn.net/wuqiqi1992/article/details/107604680
今日推荐