美文网首页
Kotlin-kotlin-android-extension被

Kotlin-kotlin-android-extension被

作者: 杨0612 | 来源:发表于2021-03-29 14:37 被阅读0次
    众所周知,添加了kotlin-android-extension插件以后,就可以直接在Kotlin中直接引用控件了,不再需要findViewById极其的方便,但同时也带来一些问题:
    1.控件错误导入

    插件通过控件名就会把控件import到当前类,但不会做有效校验。
    AActivity 使用activity_a.xml布局

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
        <TextView
            android:id="@+id/aTv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>
    

    BActivity 使用activity_b.xml布局

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
        <TextView
            android:id="@+id/bTv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>
    

    其实在AActivity导入bTv控件,也是可以编译通过的,只是运行时会报错。理论上,在layout下的所有控件,都是可以导入的,编译时不做任何有效校验,一旦控件错误导入,某个业务场景下才使用到该控件,那么bug就会藏得很深。

    2.局限性

    只能在Kotlin代码使用,而Java是没法使用的,那么Java就得用另外一套方式,对于Kotlin、Java共存的项目就会增加维护性。

    其实在Kotlin 1.4.20-M2中,JetBrains废弃了Kotlin Android Extensions编译插件,转而建议我们使用ViewBinding。

    以上分析有不对的地方,请指出,互相学习,谢谢哦!

    相关文章

      网友评论

          本文标题:Kotlin-kotlin-android-extension被

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