ButterKnife源码分析

目的:分析ButterKnife如何进行view与onClick事件的绑定

原理分析

通过观察BindView注解发现,该注解是存在于编译器的:

@Retention(CLASS) @Target(FIELD)
public @interface BindView {
  /** View ID to which the field will be bound. */
  @IdRes int value();
}

那么猜想肯定需要通过注解处理器来处理该注解注释的字段或方法。
找到引用:

    kapt "com.jakewharton:butterknife-compiler:8.8.1"

找到注解编译器源码:ButterKnifeProcessor extends AbstractProcessor{}
通过重写getSupportedAnnotationTypes方法来获取支持的注解类型:

  @Override public Set getSupportedAnnotationTypes() {
    Set types = new LinkedHashSet<>();
    for (Class annotation : getSupportedAnnotations()) {
      types.add(annotation.getCanonicalName());
    }
    return types;
  }

  private Set> getSupportedAnnotations() {
    Set> annotations = new LinkedHashSet<>();

    annotations.add(BindAnim.class);
    annotations.add(BindArray.class);
    annotations.add(BindBitmap.class);
    annotations.add(BindBool.class);
    annotations.add(BindColor.class);
    annotations.add(BindDimen.class);
    annotations.add(BindDrawable.class);
    annotations.add(BindFloat.class);
    annotations.add(BindFont.class);
    annotations.add(BindInt.class);
    annotations.add(BindString.class);
    annotations.add(BindView.class);
    annotations.add(BindViews.class);
    annotations.addAll(LISTENERS);

    return annotations;
  }

在获取到所有的上述类型后,会进入process方法进行处理:

  @Override public boolean process(Set elements, RoundEnvironment env) {
    Map bindingMap = findAndParseTargets(env);

    for (Map.Entry entry : bindingMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingSet binding = entry.getValue();

      JavaFile javaFile = binding.brewJava(sdk, debuggable);
      try {
        javaFile.writeTo(filer);
      } catch (IOException e) {
        error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
      }
    }

    return false;
  }

该方法异常简短,主要是做了很多的封装,其中BindingSet类就是一个封装了将要生成的中间类的代码的类。在该类中,会通过解析的注解的属性来将对应的语句添加到BindingSet.Builder中,也可通过其中的addMethod向中间类中添加方法。
因此findAndParseTargets方法的主要工作就是解析各个注解信息并生成对应的语句放入BindingSet中。在所有的解析完毕后,会轮询该Map集合,然后通过JavaFile来生成中间类。
下边详细看一下findAndParseTargets方法:

  private Map findAndParseTargets(RoundEnvironment env) {
    Map builderMap = new LinkedHashMap<>();
    Set erasedTargetNames = new LinkedHashSet<>();

    // Process each @BindView element.
    for (Element element : env.getElementsAnnotatedWith(BindView.class)) {
      // we don't SuperficialValidation.validateElement(element)
      // so that an unresolved View type can be generated by later processing rounds
      try {
        parseBindView(element, builderMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindView.class, e);
      }
    }
    
    // Process each annotation that corresponds to a listener.
    for (Class listener : LISTENERS) {
      findAndParseListener(env, listener, builderMap, erasedTargetNames);
    }

    // Associate superclass binders with their subclass binders. This is a queue-based tree walk
    // which starts at the roots (superclasses) and walks to the leafs (subclasses).
    Deque> entries =
        new ArrayDeque<>(builderMap.entrySet());
    Map bindingMap = new LinkedHashMap<>();
    while (!entries.isEmpty()) {
      Map.Entry entry = entries.removeFirst();

      TypeElement type = entry.getKey();
      BindingSet.Builder builder = entry.getValue();

      TypeElement parentType = findParentType(type, erasedTargetNames);
      if (parentType == null) {
        bindingMap.put(type, builder.build());
      } else {
        BindingSet parentBinding = bindingMap.get(parentType);
        if (parentBinding != null) {
          builder.setParent(parentBinding);
          bindingMap.put(type, builder.build());
        } else {
          // Has a superclass binding but we haven't built it yet. Re-enqueue for later.
          entries.addLast(entry);
        }
      }
    }

    return bindingMap;
  }

在该方法中,会处理收集每种注解类型的信息,上边只粘出了BindView和OnClick的片段。以BindView为例:

  private void parseBindView(Element element, Map builderMap,
      Set erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Start by verifying common generated code restrictions.
    boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element)
        || isBindingInWrongPackage(BindView.class, element);

    // Verify that the target type extends from View.
    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
      TypeVariable typeVariable = (TypeVariable) elementType;
      elementType = typeVariable.getUpperBound();
    }
    Name qualifiedName = enclosingElement.getQualifiedName();
    Name simpleName = element.getSimpleName();

    // Assemble information on the field.
    int id = element.getAnnotation(BindView.class).value();
    BindingSet.Builder builder = builderMap.get(enclosingElement);
    Id resourceId = elementToId(element, BindView.class, id);
    if (builder != null) {
      String existingBindingName = builder.findExistingBindingName(resourceId);
    } else {
      builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
    }

    String name = simpleName.toString();
    TypeName type = TypeName.get(elementType);
    boolean required = isFieldRequired(element);

    builder.addField(resourceId, new FieldViewBinding(name, type, required));

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement);
  }

会收集修饰字段的修饰符,字段名称,字段类型等信息,然后通过builder.addField将该字段添加到BindingSet.Builder中。
在收集到所有的类型后,最终会通过:

 JavaFile javaFile = binding.brewJava(sdk, debuggable);
 javaFile.writeTo(filer);

生成中间类。binding.brewJava方法:

  JavaFile brewJava(int sdk, boolean debuggable) {
    TypeSpec bindingConfiguration = createType(sdk, debuggable);
    return JavaFile.builder(bindingClassName.packageName(), bindingConfiguration)
        .addFileComment("Generated code from Butter Knife. Do not modify!")
        .build();
  }

就是直接调用JavaFile来创建类。而createType就是通过在解析时添加到Binding.Builder中的语句字段来生成类的代码,比如包名类名等。
最终生成的中间类代码如下:

  // Generated code from Butter Knife. Do not modify!
package com.jf.jlfund.view.activity;
import butterknife.internal.DebouncingOnClickListener;
import butterknife.internal.Utils;
import com.jf.jlfund.R;

public class FundSaleOutActivity_ViewBinding implements Unbinder {
  private FundSaleOutActivity target;

  private View view2131231970;

  @UiThread
  public FundSaleOutActivity_ViewBinding(FundSaleOutActivity target) {
    this(target, target.getWindow().getDecorView());
  }

  @UiThread
  public FundSaleOutActivity_ViewBinding(final FundSaleOutActivity target, View source) {
    this.target = target;

    View view;
    target.rootView = Utils.findRequiredViewAsType(source, R.id.rl_fundSaleOut_rootView, "field 'rootView'", RelativeLayout.class);
    target.commonTitleBar = Utils.findRequiredViewAsType(source, R.id.commonTitleBar_fundSaleOut, "field 'commonTitleBar'", CommonTitleBar.class);
    target.etAmount = Utils.findRequiredViewAsType(source, R.id.et_fundSaleOut, "field 'etAmount'", EditText.class);
    view = Utils.findRequiredView(source, R.id.tv_fundSaleOut_saleAll, "field 'tvSaleAll' and method 'onClick'");
    target.tvSaleAll = Utils.castView(view, R.id.tv_fundSaleOut_saleAll, "field 'tvSaleAll'", TextView.class);
    view2131231970 = view;
    view.setOnClickListener(new DebouncingOnClickListener() {
      @Override
      public void doClick(View p0) {
        target.onClick(p0);
      }
    });
  }

  @Override
  @CallSuper
  public void unbind() {
    FundSaleOutActivity target = this.target;
    if (target == null) throw new IllegalStateException("Bindings already cleared.");
    this.target = null;

    target.rootView = null;
    target.commonTitleBar = null;
    target.etAmount = null;
    target.tvSaleAll = null;

    view2131231970.setOnClickListener(null);
    view2131231970 = null;
  }
}

其中,Utils.findRequiredViewAsType的作用就是source.findViewById并将查找的view转换成具体的类型。

以上的工作都发生在编译器,那么如何在运行期来进行view的绑定呢?
回想每次在Activity中使用都要事先进行:

Unbinder unbinder = ButterKnife.bind(this);

bind方法:

  @NonNull @UiThread
  public static Unbinder bind(@NonNull Activity target) {
    View sourceView = target.getWindow().getDecorView();
    return createBinding(target, sourceView);
  }

看语句是先获取该Activity的DecorView,然后作为rootView进行控件的绑定:


 private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
    Class targetClass = target.getClass();
    Constructor constructor = findBindingConstructorForClass(targetClass);

    if (constructor == null) {
      return Unbinder.EMPTY;
    }

    //noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
    try {
      return constructor.newInstance(target, source);
    } catch (Exception e) {
        //...
    } 
  }

    @Nullable @CheckResult @UiThread
  private static Constructor findBindingConstructorForClass(Class cls) {
    Constructor bindingCtor = BINDINGS.get(cls);
    if (bindingCtor != null) {
      return bindingCtor;
    }
    String clsName = cls.getName();
    if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
      return null;
    }
    try {
      Class bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");
      //noinspection unchecked
      bindingCtor = (Constructor) bindingClass.getConstructor(cls, View.class);
    } catch (ClassNotFoundException e) {}
    BINDINGS.put(cls, bindingCtor);
    return bindingCtor;
  }

方法说明:

  1. 根据传入的target来获取对应的在编译器生成的target_ViewBinding类。
  2. 获取该类的构造函数
  3. 通过传入的参数执行该类的构造函数

上边方法执行完毕后,在编译期生成的类就会被执行在Activity的onCreate方法中。在回顾一下生成的类的代码片段:

    target.rootView = Utils.findRequiredViewAsType(source, R.id.rl_fundSaleOut_rootView, "field 'rootView'", RelativeLayout.class);
    target.commonTitleBar = Utils.findRequiredViewAsType(source, R.id.commonTitleBar_fundSaleOut, "field 'commonTitleBar'", CommonTitleBar.class);

其中,findRequiredViewAsType就是调用source.findViewById然后转化成指定的类型。而这个source就是我们传入的DecorView。
至此,view的绑定也就完成了。事件的绑定也类似。还有要记得,在Activity的onDestory中要调用:

 unbinder.unbind();

该操作会把注解生成的view都给置空。

总结

  1. 通过注解处理器生成对应的中间类**_ViewBinding,并将findViewById与事件点击等操作写入该类的构造函数中。
  2. 在运行期,通过在Activity的onCreate方法中bind(this)来获取该中间构造函数,并通过反射构造函数来实现view的绑定。

你可能感兴趣的:(ButterKnife源码分析)