记录一下ViewBinding的使用

背景

在学习《第一行代码第三版》中使用郭神推荐的kotlin-android-extensions感觉十分方便,但是发现每次都要在build.gradle中手动加入这个插件而不是默认有的,后来发现google已经打算在2021年9月从kotlin中弃用该模组,并且推荐使用 ViewBinding(视图绑定)代替kotlin-android-extensions。于是开始在手敲书中的代码时开始尝试使用 ViewBinding 而放弃使用extensions。

在查阅资料过程中发现了还有 DataBinding(数据绑定)的概念,在之后若使用到将会进行记录。

查阅资料:
安卓developers
简书某文章

ViewBinding

build.gradle 设置

android闭包中加入(AS4.0后的版本,与3.6的版本略微不同)

buildFeatures {
      viewBinding true
}

布局 设置

在不需要viewBinding生成绑定布局的根目录中加入

xmlns:tools="http://schemas.android.com/tools"
tools:viewBindingIgnore="true"

Activity 设置

  1. 需要通过viewBinding生成的绑定类获取binding实例
  2. setContentView()中传入binding实例的root
  3. 使用binding.{id}获取各部件

实例:

private lateinit var binding : ActivityMainBinding   #绑定类名字格式一般为layout文件的名字+Binding

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel("normal", "Normal", NotificationManager.IMPORTANCE_DEFAULT)
            val channe2 = NotificationChannel("important", "Important", NotificationManager.IMPORTANCE_HIGH)
            manager.apply {
                createNotificationChannel(channel)
                createNotificationChannel(channe2)
            }
        }
        binding.sendNotice.setOnClickListener(this)
    }

实例中的布局包含了一个id为 sendNotice 的按键

posted @ 2021-01-13 22:17  Donkiss丶  阅读(271)  评论(0编辑  收藏  举报