您可能知道,ButterKnife 是一个注释处理器,它在编译时获取您的代码,评估注释(例如@BindView)并生成代码以替换它们。
现在对于@BindView,注解处理器的实际作用是:
- 通过 ID 查找所需视图
和
- 将其转换为预期的类型。
因此,您的示例的功能等价物将是这样的:
public class FriendsHolder extends RecyclerView.ViewHolder {
private TextView textName;
private CircleImageView imageView;
private TextView textTitle;
private TextView textCompany;
FriendsHolder(View itemView) {
super(itemView);
bindViews(itemView);
}
private void bindViews(View root) {
textName = (TextView) root.findViewById(R.id.name);
imageView = (CircleImageView) root.findViewById(R.id.image);
textTitle = (TextView) root.findViewById(R.id.title);
textCompany = (TextView) root.findViewById(R.id.company);
}
}
您可以阅读更多有关底层进程的信息in this blog post 或查看some of the ButterKnife source code。
您可以看到,他们所做的基本上是在源视图上查找 ID,并尝试将其转换为从注释字段中读取的预期类型。
摘自butterknife.internal.Utils:
public static <T> T findRequiredViewAsType(View source, @IdRes int id, String who, Class<T> cls) {
View view = findRequiredView(source, id, who);
return castView(view, id, who, cls);
}
public static View findRequiredView(View source, @IdRes int id, String who) {
View view = source.findViewById(id);
if (view != null) {
return view;
}
// If view is null throw IllegalStateException
}
public static <T> T castView(View view, @IdRes int id, String who, Class<T> cls) {
try {
return cls.cast(view); // <-- casting
} catch (ClassCastException e) {
throw new IllegalStateException
// Exception handling...
}