if (requiresCast) {
builder.add(“AsType”);
}
builder.add("(source, $L", bindings.getId().code);
if (fieldBinding.isRequired() || requiresCast) {
builder.add(", $S", asHumanDescription(singletonList(fieldBinding)));
}
if (requiresCast) {
builder.add(", KaTeX parse error: Expected 'EOF', got '}' at position 39: …getRawType()); }̲ builder.add(")…L", builder.build());
return;
}
List requiredViewBindings = bindings.getRequiredBindings();
if (requiredViewBindings.isEmpty()) {
result.addStatement(“view = source.findViewById($L)”, bindings.getId().code);
} else if (!bindings.isBoundToRoot()) {
result.addStatement(“view = $T.findRequiredView(source, $L, $S)”, UTILS,
bindings.getId().code, asHumanDescription(requiredViewBindings));
}
addFieldBindings(result, bindings);
addMethodBindings(result, bindings);
}
主要是调用系统的findViewById 方法,但是你看到了findRequiredViewAsType,findRequiredView方法和castView方法,findRequiredView,findRequiredViewAsType是作者为乐代码的书写方便对findViewById的一层封装,你可以看一下源码,最后都会调用的findRequiredView方法的findViewById方法。
public static View findRequiredView(View source, @IdRes int id, String who) {
View view = source.findViewById(id);
if (view != null) {
return view;
}
String name = getResourceEntryName(source, id);
throw new IllegalStateException(“Required view '”
- name
- "’ with ID "
- id
- " for "
- who
- " was not found. If this view is optional add ‘@Nullable’ (fields) or ‘@Optional’"
- " (methods) annotation.");
}
这个castView是什么方法呢?是Class类的方法,直接转换为指定的类型
public static T castView(View view, @IdRes int id, String who, Class cls) {
try {
return cls.cast(view);
} catch (ClassCastException e) {
String name = getResourceEntryName(view, id);
throw new IllegalStateException(“View '”
- name
- "’ with ID "
- id
- " for "
- who
- " was of the wrong type. See cause for more info.", e);
}
}
说白了都是调用系统的方法。
好了到这里成员变量的赋值算是完了。
注意一点target.title target就是我们的activity或者view ;也验证了为什么是使用了类似BindView注解不能是private修饰符的另一个原因了。
接下来是方法的监听 private void addMethodBindings(MethodSpec.Builder result, ViewBindings bindings) {}方法,李 main 也是通过循环添加方法借助我们上文提到的
MethodSpec.methodBuilder构造器
for (ListenerMethod method : getListenerMethods(listener)) {
MethodSpec.Builder callbackMethod = MethodSpec.methodBuilder(method.name())
.addAnnotation(Override.class)
.addModifiers(PUBLIC)
.returns(bestGuess(method.returnType()));
String[] parameterTypes = method.parameters();
for (int i = 0, count = parameterTypes.length; i < count; i++) {
callbackMethod.addParameter(bestGuess(parameterTypes[i]), “p” + i);
//…
}
感兴趣的可以根据生成的代码来对照这查看,这里就不多说了。
最后生成的如下所示的代码。
@UiThread
public SimpleActivity_ViewBinding(f