当你在项目(Module)的build.gradle中的android{}中设置
buildFeatures { viewBinding true }
设置完sync一下,然后会在项目中看到对应的XML文件的一个继承了ViewBinding的对应绑定类。
如果不想生成,则在XML文件中设置一个tools:viewBindingIgnore="true"属性,即可忽略不生成对应绑定类。
如果你的XML是Activity生成的,那么对应绑定类的名字开头就是Activity,反之Fragment。然后就是对应Activity或者Fragment类名,最后再加一个Binding,就是这个自动生成的绑定类的名字。
就可以在程序中调用此名字,也就是一个类,可以实例化并调用此类中的方法。
这个绑定类有继承关系吗?
它只实现了ViewBinding这个接口。
public interface ViewBinding {
/**
* Returns the outermost {@link View} in the associated layout file. If this binding is for a
* {@code <merge>} layout, this will return the first view inside of the merge tag.
*/
@NonNull
View getRoot();
}
这个绑定类的成员变量有什么呢?
有对应XML中各个控件变量。
根布局rootView是private的,其他控件都是public的。
且全为final修饰。
这个绑定类的构造?
给上面的控件赋值的,有多少个控件就有多少个参数。
有什么方法?
第一个方法:getRoot()——获取根布局
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
第二个方法:inflate()——加载对应XML布局文件
@NonNull
public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_main, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
第三个方法:bind()——绑定文件里面的控件
@NonNull
public static ActivityMainBinding 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.bottomNavigationView;
BottomNavigationView bottomNavigationView = ViewBindings.findChildViewById(rootView, id);
if (bottomNavigationView == null) {
break missingId;
}
id = R.id.fabPlus;
FloatingActionButton fabPlus = ViewBindings.findChildViewById(rootView, id);
if (fabPlus == null) {
break missingId;
}
id = R.id.viewPager;
ViewPager2 viewPager = ViewBindings.findChildViewById(rootView, id);
if (viewPager == null) {
break missingId;
}
return new ActivityMainBinding((ConstraintLayout) rootView, bottomNavigationView, fabPlus,
viewPager);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
通过根布局和ID找控件,具体在这个方法中执行。
@Nullable
public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
if (!(rootView instanceof ViewGroup)) {
return null;
}
final ViewGroup rootViewGroup = (ViewGroup) rootView;
final int childCount = rootViewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
final T view = rootViewGroup.getChildAt(i).findViewById(id);
if (view != null) {
return view;
}
}
return null;
}