kotlin-android-extension作用
kotlin-android-extension插件以后,就可以直接在Kotlin中直接引用控件了,不再需要findViewById极其的方便。
kotlin-android-extension问题:
- 控件错误导入 插件可以把控件import进来,但不会做有效校验,即使控件不是当前xml的。 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>
import kotlinx.android.synthetic.main.使用activity_b.*//导入了BActivity的布局
class AActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_a)
bTv.text = "test"//可以使用activity_b布局控件
- 以上代码可以编译通过,但是运行会报错。理论上,在layout下所有布局文件的控件都可以导入,一旦控件错误导入,就会有bug隐患。
- 局限性 只能在Kotlin代码使用,而Java是没法使用的,那么Java就得用另外一套方式,对于Kotlin、Java共存的项目就会增加维护性。
总结
- 其实在Kotlin 1.4.20-M2中,JetBrains废弃了Kotlin Android Extensions编译插件,转而建议我们使用ViewBinding。
以上分析有不对的地方,请指出,互相学习,谢谢哦!