通过视图绑定功能,您可以更轻松地编写可与视图交互的代码。在模块中启用视图绑定之后,系统会为该模块中的每个 XML 布局文件生成一个绑定类。绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。
在大多数情况下,视图绑定会替代 findViewById。
请将 viewBinding 元素添加到其 build.gradle 文件中
viewBinding {
enabled = true
}
如果您希望在生成绑定类时忽略某个布局文件,请将 tools:viewBindingIgnore="true" 属性添加到相应布局文件的根视图中
<LinearLayout
...
tools:viewBindingIgnore="true" >
...
</LinearLayout>
数据绑定库是一种支持库,借助该库,您可以使用声明性格式(而非程序化地)将布局中的界面组件绑定到应用中的数据源。
布局通常是使用调用界面框架方法的代码在 Activity 中定义的。例如,以下代码调用 findViewById() 来查找 TextView 微件并将其绑定到 viewModel 变量的 userName 属性:
dataBinding {
enabled = true
}

回顾知识点:Activity布局中添加Fragment:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fg"/>
//Fragment管理器 FragmentManager fragmentManager=getSupportFragmentManager(); //事务 FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); //增删改查替换 fragmentTransaction.replace(R.id.fg,new OneFragment()); //提交 fragmentTransaction.commit();
添加DatabindingConvert插件
布局中Ait+Insert选中
Day1知识小结:


Fragment绑定添加视图方法:
本文介绍了如何在Android开发中利用视图绑定功能,替代findViewById,实现声明式数据绑定,以及如何在Activity中管理Fragment和添加DatabindingConvert插件。通过视图绑定,开发者可以更高效地连接布局与数据源,提升代码可读性和维护性。
660





