在大多数情况下,视图绑定会替代
findViewById
。
视图绑定功能可按模块启用。要在某个模块中启用视图绑定,请将 viewBinding
元素添加到其 build.gradle
文件中,如下例所示:
android {
...
viewBinding {
enabled = true
}
}
用法
将 XML 文件的名称转换为驼峰式大小写,并在末尾添加“Binding”一词
例如,假设某个布局文件的名称为
result_profile.xml
:所生成的绑定类的名称就为ResultProfileBinding
每个绑定类还包含一个
getRoot()
方法, 用于为相应布局文件的根视图提供直接引用
在Activity中使用视图绑定
如需设置绑定类的实例以供 Activity 使用,请在 Activity 的 onCreate() 方法中执行以下步骤:
- 调用生成的绑定类中包含的静态
inflate()
方法。此操作会创建该绑定类的实例以供 Activity 使用。 - 通过调用
getRoot()
方法或使用 Kotlin 属性语法获取对根视图的引用。 - 将根视图传递到 setContentView(),使其成为屏幕上的活动视图。
private ResultProfileBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ResultProfileBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
}
在 Fragment 中使用视图绑定
如需设置绑定类的实例以供 Fragment 使用,请在 Fragment 的onViewCreated 方法中执行以下步骤:
调用生成的绑定类中包含的静态 bind()
方法。此操作会创建该绑定类的实例以供 Fragment 使用。
public class HomeFragment extends Fragment {
private FragmentHomeBinding bind;
public HomeFragment() {
super(R.layout.fragment_home);//传入布局
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//在这个创建viewBinding,通过bind方法,绑定已经创建的view对象
bind = FragmentHomeBinding.bind(view);
}
}
您现在即可使用该绑定类的实例来引用任何视图:
bind.tv.setText("Hello world");