如何使用
要求
需要在 Android Studio 3.6 Canary 11 及更高版本中可用
设置ViewBinding
- 在 build.gradle 文件中设置是否启用 ViewBinding
android {
...
viewBinding {
enabled = true
}
}
- 如果希望生成绑定类时忽略某个布局文件,可以设置 tools:viewBindingIgnore=“true”
<LinearLayout
...
tools:viewBindingIgnore="true" >
...
</LinearLayout>
使用 ViewBinding
- 启用 ViewBinding 之后,系统会为启动模块的所有布局文件生成一个绑定类,生成绑定类的命名规则为:将 XML 文件的名称转换为驼峰式大小写,并在末尾添加“Binding”一词;比如 activity_main 生成的绑定类为 ActivityMainBinding
- 在Activity 中使用 ViewBinding
<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=".MainActivity">
<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
private lateinit var binding: lv
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
viewBinding.tvHello.text = "Hello World!"
}
- 在Fragment 中使用
private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ResultProfileBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onDestroyView() {
super.onDestroyView()
// 注意:Fragment 的存在时间比其视图长。请务必在 Fragment 的 onDestroyView() 方法中清除对绑定类实例的所有引用。
_binding = null
}
优点:
与 findViewById 对比有如下优点:
- Null 安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 Null 指针异常的风险。此外,如果视图仅出现在布局的某些配置中,则绑定类中包含其引用的字段会使用 @Nullable 标记。
- 类型安全:每个绑定类中的字段均具有与它们在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。
这些差异意味着布局和代码之间的不兼容将会导致构建在编译时(而非运行时)失败。