binding.root 是通过 Data Binding 绑定布局文件后生成的根布局对象,可以在代码中使用它来访问根布局中的子 View。以下是一个示例:
在 Activity 或 Fragment 中,使用 DataBindingUtil.inflate 方法将布局文件与 Data Binding 绑定:
MyLayoutBinding binding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.my_layout,
parentView,
false);
然后就可以使用 binding.root 访问布局文件中的 root_layout,以及其中的子 View,例如 TextView:
// 访问根布局中的子 View
LinearLayout rootLayout = binding.root.findViewById(R.id.root_layout);
TextView textView = binding.root.findViewById(R.id.text_view);
如果当前布局文件中只使用了一个 View,可以直接使用 binding.getRoot() 获取根布局对象。