理解kotlin-android-extension被废弃

kotlin-android-extensions插件的实现原理:kotlin-android-extensions插件会帮我们生成一个_$_findCachedViewById()函数(使用这种奇怪的命名方式是为了防止和开发者定义的函数名冲突)。在这个函数中首先会尝试从一个HashMap中获取传入的资源id参数所对应的控件实例缓存,如果还没有缓存的话,就调用findViewById()函数来查找控件实例,并写入HashMap缓存当中。这样当下次再获取相同控件实例的话,就可以直接从HashMap缓存中获取了。

存在着一些问题比如 每一个Activity都需要使用一个额外的HashMap数据结构来存储所有控件的实例,在程序上降低了运行效率,存在着很多“坑”

ViewBinding代替了kotlin-android-extension它的目的就是就是为了避免编写findViewById,这和它另外一个非常复杂的兄弟DataBinding相比有明显的区别。

使用ViewBinding:1.新建一个ViewBindingTest项目

默认布局加入组文件

  <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

build.gradle的Module文件配置

buildFeatures {

viewBinding true

}

在Activity中使用ViewBinding

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)

      setContentView(binding.root)//binding.root   //获取activity_main.xml中的根元素

binding.textView.text ="ViewBinding

}

}"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值