前言
在Android
开发过程中,我们经常要做的就是初始化控件,最原始的方式是findViewById
,后面又出现了Butternikef
,接着是kotlin
推出的kotlin-android-extensions
插件,可惜的是kotlin-android-extensions插件已经废弃,官方提倡用ViewBinding
代替。那么今天就来讲讲ViewBinding
的使用。
今天涉及内容:
-
ViewBinding
是啥 -
ViewBinding
使用配置 -
ViewBinding
在Activity
中使用 -
ViewBinding
使用注意及忽略
一. ViewBinding 是啥
ViewBinding
简单来说就是实现控件初始化的插件,起到视图绑定作用,代替繁琐的findViewById
来初始化控件的框架。
二. ViewBinding 使用配置
在使用ViewBinding
之前,你需要在app_module
对应的build.gradle
中添加如下配置:
android {
buildFeatures{
viewBinding true
}
//其他代码省略
//......
}
三. ViewBinding 在 Activity 中使用
为了后面描述方便,下面先给出MainActivity
对应的布局文件activity_main.xml
代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<TextView
android:id="@+id/tv_name"
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"
app:layout_constraintVertical_bias="0.08" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="点击"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
以前我们是这样在MainActivity
中加载布局和初始化控件的:
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var mTvName: TextView
private lateinit var mBtn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initData()
setListener()
}
private var initData = {
mTvName = findViewById(R.id.tv_name)
mBtn = findViewById(R.id.btn)
mTvName.text = "我是神"
}
private var setListener = {
mBtn.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v.id) {
R.id.btn -> {
LogUtil.i("====我点击了=====")
}
else -> {}
}
}
}
在使用ViewBinding
以后,我们是这样在MainActivity
中初始化控件的: