一.简介
ViewBinding是Android Studio 3.6推出的新特性,旨在替代findViewById(内部实现还是使用findViewById)。通过ViewBinding,可以更轻松地编写可与视图交互的代码。在模块中启用ViewBinding之后,系统会为该模块中的每个 XML 布局文件生成一个绑定类。绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。
注:ViewBinding&DataBinding区别
1.两者都生成可用于直接引用视图的绑定类。
2.View binding旨在处理更简单的用例,有以下特点
<1> 更快的编译: 视图绑定不需要注释处理,因此编译时间更快。
<2> 易用性: 视图绑定不需要特别标记的 XML 布局文件,因此在您的应用程序中采用它的速度更快。在模块中启用视图绑定后,它会自动应用于该模块的所有布局。
<3> 视图绑定不支持布局变量或布局表达式,因此它不能用于直接从 XML 布局文件声明动态 UI 内容。
3.DataBinding可以支持变量刷新,布局表达式,可以直接从 XML 布局文件声明动态 UI 内容。
二.依赖及文件路径
1.添加依赖
模块build.gradle文件android节点下添加如下代码
android {
viewBinding{
enabled = true
}
}
在 Android Studio 4.0 中,viewBinding 变成属性被整合到了 buildFeatures 选项中,所以配置要改成
android {
buildFeatures {
viewBinding = true
}
}
2.文件路径
配置好上述Gradle,成功编译后,在相应Module中对应的文件夹下回看到生成的内容
三.Activity使用
1.Activity代码
public class BaseModuleMainActivity extends AppCompatActivity {
ActivityBaseModuleMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityBaseModuleMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.tvBaseModule.setText("我是TextView");
binding.tvBaseModule.setOnClickListener(v -> LoggerUtils.logD("BaseModuleMainActivity", "TextView点击..."));
}
}
2.Activity布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_base_module"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_100"
android:background="@color/purple_200"
android:gravity="center"
android:textColor="@color/white"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.结果
BaseModuleMainActivity TextView点击...
4.说明
原本默认情况下Activity的onCreate方法是这样的
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
}
即,使用setContentView()方法设置布局。而使用ViewBinding则需要在setContentView()方法前获取XXXBinding对象。
binding = ActivityBaseModuleMainBinding.inflate(getLayoutInflater());
然后调用XXXBinding对象的getRoot方法获取XXXView设置到setContentView()方法。
setContentView(binding.getRoot());
5.源码
生成的XXXBinding文件是按照Activity布局的名称驼峰生成的。
比如上述我们的Activity布局名称是activity_base_module_main,
那么生成的Binding文件名称则是ActivityBaseModuleMainBinding。
public final class ActivityBaseModuleMainBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final TextView tvBaseModule;
private ActivityBaseModuleMainBinding(@NonNull ConstraintLayout rootView,
@NonNull TextView tvBaseModule) {
this.rootView = rootView;
this.tvBaseModule = tvBaseModule;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static ActivityBaseModuleMainBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ActivityBaseModuleMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_base_module_main, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ActivityBaseModuleMainBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.tv_base_module;
TextView tvBaseModule = rootView.findViewById(id);
if (tvBaseModule == null) {
break missingId;
}
return new ActivityBaseModuleMainBinding((ConstraintLayout) rootView, tvBaseModule);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
四.Fragment使用
1.Fragment代码
public class BaseModuleMainFragment extends Fragment {
FragmentBaseModuleMainBinding binding;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoggerUtils.logD("BaseModuleMainFragment", "onCreate方法执行...");
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentBaseModuleMainBinding.inflate(inflater, container, false);
LoggerUtils.logD("BaseModuleMainFragment", "onCreateView方法执行...");
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.tv01.setText("我是textView");
binding.tv01.setOnClickListener(v -> LoggerUtils.logD("BaseModuleMainFragment", "TextView点击..."));
binding.btn01.setText("我是Button");
binding.btn01.setOnClickListener(v -> LoggerUtils.logD("BaseModuleMainFragment", "Button点击..."));
LoggerUtils.logD("BaseModuleMainFragment", "onViewCreated方法执行...");
}
}
2.Fragment布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/tv_01"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_100"
android:background="@color/purple_200"
android:gravity="center"
android:textColor="@color/white"
tools:ignore="MissingConstraints" />
<Button
android:id="@+id/btn_01"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_100"
android:background="@color/purple_500"
app:layout_constraintTop_toBottomOf="@+id/tv_01"
android:layout_marginTop="10dp"
android:gravity="center"
android:textColor="@color/white"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.结果
### 初始化打印内容 ###
onCreate方法执行...
onCreateView方法执行...
onViewCreated方法执行...
### 点击TextView打印内容 ###
TextView点击...
### 点击Button打印内容 ###
Button点击...
4.说明
原本默认情况下Fragment的onCreateView方法是这样的
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_base_module_main, container, false);
initView(view);
return view;
}
使用ViewBinding后变成
binding = FragmentBaseModuleMainBinding.inflate(inflater, container, false);
return binding.getRoot();
5.源码
public final class FragmentBaseModuleMainBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final Button btn01;
@NonNull
public final TextView tv01;
private FragmentBaseModuleMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button btn01,
@NonNull TextView tv01) {
this.rootView = rootView;
this.btn01 = btn01;
this.tv01 = tv01;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static FragmentBaseModuleMainBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static FragmentBaseModuleMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.fragment_base_module_main, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static FragmentBaseModuleMainBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.btn_01;
Button btn01 = rootView.findViewById(id);
if (btn01 == null) {
break missingId;
}
id = R.id.tv_01;
TextView tv01 = rootView.findViewById(id);
if (tv01 == null) {
break missingId;
}
return new FragmentBaseModuleMainBinding((ConstraintLayout) rootView, btn01, tv01);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
五.Dialog使用
1.Dialog代码
public class PrivacyAgreementDialog extends Dialog implements View.OnClickListener {
private IDialogCallback mIDialogCallback;
private DialogPrivacyagreementBinding binding;
public PrivacyAgreementDialog(Activity activity) {
super(activity, R.style.dialog_style);
binding = DialogPrivacyagreementBinding.inflate(getLayoutInflater());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(binding.getRoot());
binding.tvContent1.setText("内容1111");
binding.tvContent2.setText("内容222");
binding.tvCancel.setOnClickListener(this);
binding.tvSure.setOnClickListener(this);
setCancelable(false);//点击外部 对话框不消失
}
/**
* 点击事件
*/
@Override
public void onClick(View v) {
if (AntiShakeUtils.isInvalidClick(v)) return;
if (v.getId() == R.id.tvCancel && null != mIDialogCallback) {
mIDialogCallback.onCancelClick();
} else if (v.getId() == R.id.tvSure && null != mIDialogCallback) {
mIDialogCallback.onSureClick();
}
}
/**
* 设置回调监听
*/
public void setDialogListener(IDialogCallback dialogListener) {
mIDialogCallback = dialogListener;
}
}
2.布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/transparent"
android:gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dp_20"
android:layout_marginRight="@dimen/dp_20"
android:background="@drawable/drawable_while_bg_while_line_r3"
android:orientation="vertical">
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_45"
android:gravity="center"
android:text="@string/privacy_agreement_textView01"
android:textColor="#000000"
android:textSize="@dimen/text_dp_14"
tools:ignore="SpUsage" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dp_15"
android:layout_marginTop="@dimen/dp_10"
android:layout_marginRight="@dimen/dp_15"
android:layout_marginBottom="@dimen/dp_10"
android:orientation="vertical">
<TextView
android:id="@+id/tvContent1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="@dimen/dp_5"
android:textColor="#FF37414E"
android:textSize="@dimen/text_dp_14"
tools:ignore="SpUsage" />
<TextView
android:id="@+id/tvContent2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="@dimen/dp_5"
android:textColor="#FF37414E"
android:textSize="@dimen/text_dp_14"
tools:ignore="SpUsage" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/dp_45"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="@+id/tvCancel"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="center"
android:singleLine="true"
android:text="@string/privacy_agreement_textView02"
android:textColor="#FF37414E"
android:textSize="@dimen/text_dp_14"
tools:ignore="SpUsage" />
<TextView
android:id="@+id/tvSure"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="center"
android:singleLine="true"
android:text="@string/privacy_agreement_textView03"
android:textColor="#FF37414E"
android:textSize="@dimen/text_dp_14"
tools:ignore="SpUsage" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
3.源码
public final class DialogPrivacyagreementBinding implements ViewBinding {
@NonNull
private final LinearLayout rootView;
@NonNull
public final TextView tvCancel;
@NonNull
public final TextView tvContent1;
@NonNull
public final TextView tvContent2;
@NonNull
public final TextView tvSure;
@NonNull
public final TextView tvTitle;
private DialogPrivacyagreementBinding(@NonNull LinearLayout rootView, @NonNull TextView tvCancel,
@NonNull TextView tvContent1, @NonNull TextView tvContent2, @NonNull TextView tvSure,
@NonNull TextView tvTitle) {
this.rootView = rootView;
this.tvCancel = tvCancel;
this.tvContent1 = tvContent1;
this.tvContent2 = tvContent2;
this.tvSure = tvSure;
this.tvTitle = tvTitle;
}
@Override
@NonNull
public LinearLayout getRoot() {
return rootView;
}
@NonNull
public static DialogPrivacyagreementBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static DialogPrivacyagreementBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.dialog_privacyagreement, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static DialogPrivacyagreementBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.tvCancel;
TextView tvCancel = rootView.findViewById(id);
if (tvCancel == null) {
break missingId;
}
id = R.id.tvContent1;
TextView tvContent1 = rootView.findViewById(id);
if (tvContent1 == null) {
break missingId;
}
id = R.id.tvContent2;
TextView tvContent2 = rootView.findViewById(id);
if (tvContent2 == null) {
break missingId;
}
id = R.id.tvSure;
TextView tvSure = rootView.findViewById(id);
if (tvSure == null) {
break missingId;
}
id = R.id.tvTitle;
TextView tvTitle = rootView.findViewById(id);
if (tvTitle == null) {
break missingId;
}
return new DialogPrivacyagreementBinding((LinearLayout) rootView, tvCancel, tvContent1,
tvContent2, tvSure, tvTitle);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
六.Adapter使用
1.Adapter代码
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final List<String> mList;
private final LayoutInflater mInflater;
public MyAdapter(Activity activity, List<String> list) {
mList = list;
mInflater = LayoutInflater.from(activity);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ItemMyRecyclerviewBinding binding = ItemMyRecyclerviewBinding.inflate(mInflater, parent, false);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.textView.setText(mList.get(position));
holder.itemView.setOnClickListener(v -> LoggerUtils.logD("MyAdapter", "Item点击..."));
}
@Override
public int getItemCount() {
return mList.size();
}
/**
* ViewHolder类
*/
static class ViewHolder extends RecyclerView.ViewHolder {
private ItemMyRecyclerviewBinding binding;
private final TextView textView;
public ViewHolder(ItemMyRecyclerviewBinding binding) {
super(binding.getRoot());
textView = binding.tvItem;
}
}
}
2.Item布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="110dp">
<TextView
android:id="@+id/tv_item"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginBottom="10dp"
android:background="@color/purple_200"
android:gravity="center"
android:textColor="@color/white"
tools:ignore="MissingConstraints"
tools:text="我是Item内容" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.源码
public final class ItemMyRecyclerviewBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final TextView tvItem;
private ItemMyRecyclerviewBinding(@NonNull ConstraintLayout rootView, @NonNull TextView tvItem) {
this.rootView = rootView;
this.tvItem = tvItem;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static ItemMyRecyclerviewBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ItemMyRecyclerviewBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.item_my_recyclerview, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ItemMyRecyclerviewBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.tv_item;
TextView tvItem = rootView.findViewById(id);
if (tvItem == null) {
break missingId;
}
return new ItemMyRecyclerviewBinding((ConstraintLayout) rootView, tvItem);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
七.include标签使用
1.include标签所在的布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_include_flags"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_100"
android:background="@color/purple_500"
android:gravity="center"
android:textColor="@color/white"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.Activity布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<include
android:id="@+id/include_layout"
layout="@layout/include_flags"/>
</androidx.constraintlayout.widget.ConstraintLayout>
3.Activity代码
public class BaseModuleMainActivity extends AppCompatActivity {
ActivityBaseModuleMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityBaseModuleMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.includeLayout.tvIncludeFlags.setText("我是Include标签引入的布局");
}
}
4.说明
include 标签必须设置id,使用时直接使用该id就可以找到include标签引入的布局了
八.include标签内有merge标签使用
1.include标签所在的布局
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/include_merge_button1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginTop="10dp"
android:background="@color/purple_200"
android:textColor="#FFFFFF" />
<Button
android:id="@+id/include_merge_button2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginTop="10dp"
android:background="@color/purple_500"
android:textColor="#FFFFFF" />
</merge>
2.Activity布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/include_flags" />
</LinearLayout>
3.Activity代码
public class BaseModuleMainActivity extends AppCompatActivity {
ActivityBaseModuleMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityBaseModuleMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
IncludeFlagsBinding mergeBinding = IncludeFlagsBinding.bind(binding.getRoot());
mergeBinding.includeMergeButton1.setText("TextView001");
mergeBinding.includeMergeButton2.setText("TextView002");
}
}
4.说明
<1> include 标签带 merge 标签,需要通过bind()将merge布局绑定到主布局上。
九.某些文件不想使用ViewBinding
如果为Module启用了视图绑定,则会为Module包含的每个XML布局文件生成一个绑定类。绑定类的名称是通过将XML文件的名称转换为 Pascal 大小写并在末尾添加Binding一词来生成的。
如果那个布局文件不需要生成绑定类(不想用这个功能)。可以将该布局的根视图中加入以下代码
tools:viewBindingIgnore="true"
添加改属性前
添加改属性后
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:viewBindingIgnore="true"
android:orientation="vertical">
<include layout="@layout/include_flags" />
</LinearLayout>
十.原理
ViewBinding的原理就是 通过gradle插件在编译的中增加了新功能,当某个module开启ViewBinding功能后,编译的时候就去扫描此模块下的layout文件,生成对应的binding类。
文件路径
源码
public final class ActivityBaseModuleMainBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final TextView tvBaseModule;
private ActivityBaseModuleMainBinding(@NonNull ConstraintLayout rootView,
@NonNull TextView tvBaseModule) {
this.rootView = rootView;
this.tvBaseModule = tvBaseModule;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static ActivityBaseModuleMainBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ActivityBaseModuleMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_base_module_main, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ActivityBaseModuleMainBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.tv_base_module;
TextView tvBaseModule = rootView.findViewById(id);
if (tvBaseModule == null) {
break missingId;
}
return new ActivityBaseModuleMainBinding((ConstraintLayout) rootView, tvBaseModule);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
源码中可以看出,最终使用的仍然是findViewById,ViewBinding通过编译时扫描layout文件生成ViewBinding绑定类。
与findViewById相比优点
<1> 空安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 Null 指针异常的风险。此外,如果视图仅出现在布局的某些配置中(比如横竖屏布局内容差异),则绑定类中包含其引用的字段会使用 @Nullable 标记。
<2> 类型安全:每个绑定类中的字段均具有与它们在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。