ViewBinding - 视图绑定
源:视图绑定
视图绑定功能可让您更轻松地编写与视图交互的代码。 在模块中启用视图绑定后,它会为该模块中显示的每个 XML 布局文件生成一个绑定类。 绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。
开始使用
视图绑定是按模块启用的。如需在模块中启用视图绑定,请在模块的 build.gradle 文件中将 viewBinding 构建选项设置为 true ,如下所示:
android {
buildFeatures {
viewBinding = true
}
}启用之后,一般不需要额外修改布局文件,系统会为该模块包含的每个 XML 布局文件生成一个绑定类。 如果您希望在生成绑定类时忽略某个布局文件,请将 tools:viewBindingIgnore="true" 属性添加到该布局文件的根视图中:
<LinearLayout
tools:viewBindingIgnore="true">
</LinearLayout>如果为某个模块启用了视图绑定,系统会为该模块包含的每个 XML 布局文件生成一个绑定类。每个绑定类都包含对根视图以及具有 ID 的所有视图的引用。系统会通过以下方式生成绑定类的名称:将 XML 文件的名称转换为 Pascal 大小写形式,并在末尾添加“Binding”一词。
例如,假设有一个名为 result_profile.xml 的布局文件,其中包含以下内容:
<LinearLayout ... >
<TextView android:id="@+id/name" />
<ImageView android:cropToPadding="true" />
<Button android:id="@+id/button"
android:background="@drawable/rounded_button" />
</LinearLayout>所生成的绑定类的名称就为 ResultProfileBinding。此类有两个字段:一个是名为 name 的 TextView,另一个是名为 button 的 Button。 布局中的 ImageView 没有 ID,因此绑定类中没有对其的引用。
每个绑定类还包含一个 getRoot() 方法,用于提供相应布局文件的根视图的直接引用。 在此示例中,ResultProfileBinding 类中的 getRoot() 方法会返回 LinearLayout 根视图。
在 Activity 中使用视图绑定
传统方式
class MainActivity : AppCompatActivity() {
private val viewModel: UserViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView: TextView = findViewById(R.id.name)
val button: TextView = findViewById(R.id.button)
textView.text = viewModel.userName
button.setOnClickListener {
viewModel.userClicked()
}
}
}视图绑定方式
如需设置绑定类的实例以用于 activity,请在 activity 的 onCreate() 方法中执行以下步骤:
- 调用生成的绑定类中包含的静态
inflate()方法。此操作会创建该绑定类的实例以供 Activity 使用。 - 通过调用
getRoot()方法或使用Kotlin属性语法获取对根视图的引用。 - 将根视图传递给
setContentView(),使其成为屏幕上的活动视图
class MainActivity : AppCompatActivity() {
private lateinit var binding: ResultProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ResultProfileBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//现在即可使用该绑定类的实例来引用任何视图:
binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }
}
}在 Fragment 中使用视图绑定
如需设置绑定类的实例,以便与 fragment 配合使用,请在 fragment 的 onCreateView() 方法中执行以下步骤:
- 调用生成的绑定类中包含的静态
inflate()方法。此操作会创建该绑定类的实例以供 Fragment 使用。 - 通过调用
getRoot()方法或使用Kotlin属性语法获取对根视图的引用。 - 从
onCreateView()方法返回根视图,使其成为屏幕上的活动视图。
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()
_binding = null
}⭐ 注意
Fragment 的存在时间比其视图长。请务必在 fragment 的 onDestroyView() 方法中清理对绑定类实例的任何引用。
您现在即可使用该绑定类的实例来引用任何视图:
binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }⭐ 注意
inflate() 方法需要您传入LayoutInflater。 如果布局已膨胀(如在 onViewCreated 之后),您可以改为调用绑定类的静态 bind() 方法
private var _binding: ResultProfileBinding? = null
private val binding get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = ResultProfileBinding.bind(view)
}
override fun onDestroyView() {
// Consider not storing the binding instance in a field, if not needed.
_binding = null
super.onDestroyView()
}在 RecycleView 中使用视图绑定
传统方式
class MyViewHolder(
private val rootView: View
) : RecyclerView.ViewHolder(rootView){
fun bindView(){
}
}
class MyAdapter(): RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val rootView = LayoutInflater.from(parent.context).inflate(R.layout.item_system_test,parent,false)
return MyViewHolder(rootView)
}
override fun getItemCount(): Int {
TODO("Not yet implemented")
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindView()
}
}视图绑定方式
class MyViewHolder(
private val binding: ItemSystemTestBinding
) : RecyclerView.ViewHolder(binding.root){
fun bindView(data: String){
binding.title.text = data
}
}
class MyAdapter(private val dataList: List<String>): RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding = ItemSystemTestBinding.inflate(
LayoutInflater.from(parent.context),
parent, false
)
return MyViewHolder(binding)
}
override fun getItemCount(): Int = dataList.size
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindView(dataList[position])
}
}针对不同配置提供提示
当您通过多种配置声明视图时,有时根据特定布局使用不同的视图类型是合理的。以下代码段显示了一个示例:
# in res/layout/example.xml
<TextView android:id="@+id/user_bio" />
# in res/layout-land/example.xml
<EditText android:id="@+id/user_bio" />在这种情况下,您可能希望生成的类公开 TextView 类型的字段 userBio,因为 TextView 是通用基类。 由于技术限制,视图绑定代码生成器无法确定情况,而是改为生成 View 字段。 这需要稍后使用 binding.userBio as TextView 转换字段。
为了绕过此限制,视图绑定支持 tools:viewBindingType 属性,可让您告知编译器在生成的代码中使用什么类型。 在前面的示例中,您可以使用此属性让编译器将字段生成为 TextView:
# in res/layout/example.xml (unchanged)
<TextView android:id="@+id/user_bio" />
# in res/layout-land/example.xml
<EditText android:id="@+id/user_bio" tools:viewBindingType="TextView" />在另一个示例中,假设您有两个布局,一个包含 BottomNavigationView,另一个包含 NavigationRailView。这两个类都会扩展 NavigationBarView,其中包含大部分实现细节。 如果您的代码不需要确切地知道当前布局中存在哪个子类,您可以使用 tools:viewBindingType 在两个布局中将生成的类型设置为 NavigationBarView:
# in res/layout/navigation_example.xml
<BottomNavigationView android:id="@+id/navigation" tools:viewBindingType="NavigationBarView" />
# in res/layout-w720/navigation_example.xml
<NavigationRailView android:id="@+id/navigation" tools:viewBindingType="NavigationBarView" />视图绑定在生成代码时无法验证此属性的值。为避免编译时错误和运行时错误,该值必须满足以下条件:
- 该值必须是继承自
android.view.View的类。 - 该值必须是放置它的代码的父类。例如,以下值不起作用:
<TextView tools:viewBindingType="ImageView" /> <!-- ImageView is not related to TextView. -->
<TextView tools:viewBindingType="Button" /> <!-- Button is not a superclass of TextView. -->- 最终类型必须在所有配置中一致地解析。
与 findViewById 的区别
与使用 findViewById 相比,视图绑定具有一些很显著的优点:
Null 安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 null 指针异常的风险。 此外,当视图仅存在于布局的某些配置中时,绑定类中包含其引用的字段会标记为
@Nullable。类型安全:每个绑定类中的字段都具有与其在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。 这些差异意味着布局和代码不兼容,会导致 build 在编译时(而不是运行时)失败。
扩展
项目中如果使用到了视图绑定,则可以进一步封装一些通用类来简化样板代码,比如:
// BaseBindingFragment
abstract class BaseBindingFragment<VB : ViewBinding> : Fragment() {
protected var binding: VB? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return getViewBinding(inflater, container).also {
binding = it
}.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.onViewCreated()
}
protected open fun VB.onViewCreated() {
}
protected open fun VB.onDestroyView() {
}
override fun onDestroyView() {
binding?.onDestroyView()
binding = null
super.onDestroyView()
}
protected abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
}
//BaseDialogBindingFragment
abstract class BaseDialogBindingFragment<VB : ViewBinding> : DialogFragment() {
protected var binding: VB? = null
//是否全屏窗口
protected open val isFullScreen = false
//窗口背景调暗度
protected open val dimAmount = 0.5f
//窗口透明度
protected open val alpha = 1.0f
protected open val cancelable = false
protected open val canceledOnTouchOutside = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (isFullScreen) {
setStyle(STYLE_NO_TITLE, android.R.style.Theme_Light_NoTitleBar_Fullscreen)
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.apply {
requestWindowFeature(Window.FEATURE_NO_TITLE)
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setCancelable(cancelable)
setCanceledOnTouchOutside(canceledOnTouchOutside)
}
return dialog
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return getViewBinding(inflater, container).also {
binding = it
}.root
}
override fun onStart() {
super.onStart()
//透明背景
dialog?.window?.also {
it.attributes = it.attributes?.also { param ->
param.gravity = Gravity.CENTER
//窗口透明度
param.alpha = alpha
//窗口背景调暗度
param.dimAmount = dimAmount
param.flags = param.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.onViewCreated()
}
protected open fun VB.onViewCreated() {
}
override fun onDestroyView() {
binding = null
super.onDestroyView()
}
protected abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
}使用时只需类似这样写:
class BackFragment: BaseBindingFragment<BackFragmentBinding>(){
override fun getViewBinding(
inflater: LayoutInflater,
container: ViewGroup?
): BackFragmentBinding {
return BackFragmentBinding.inflate(inflater, container, false)
}
override fun BackFragmentBinding.onViewCreated() {
//直接使用 binding 进行操作
}
}