美文网首页
Android ButterKnife 笔记

Android ButterKnife 笔记

作者: silencefun | 来源:发表于2017-12-04 13:36 被阅读28次

2017年11月17日 18:52:14 使用、原码分析

项目github地址:https://github.com/JakeWharton/butterknife

  • ButterKnife 优势

    1、强大的View绑定和Click事件处理功能,简化代码,提升开发效率
    2、方便的处理Adapter里的ViewHolder绑定问题
    3、运行时不会影响APP效率,使用配置方便
    4、代码清晰,可读性强

在build.gradle中添加以下依赖

annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.0'
compile 'com.jakewharton:butterknife-annotations:8.8.0'
compile 'com.jakewharton:butterknife:8.8.0'

注入框架都是运行时注解,即声明注解的生命周期为RUNTIME,然后在运行的时候通过反射完成注入,这种方式虽然简单,但是这种方式多多少少会有性能的损耗。那么有没有一种方法能解决这种性能的损耗呢? 没错,答案肯定是有的,那就是Butterknife用的APT(Annotation Processing Tool)编译时解析技术。
Activity : 在onCreate bind,onDestory unbind;
Fragment:在onCreateView bind,在onDestroyView unbind

ButterKnife自动生成插件安装:

在AndroidStudio->File->Settings->Plugins->搜索Zelezny下载添加就行 ,可以快速生成对应组件的实例对象,不用手动写。使用时,在要导入注解的Activity 或 Fragment 或 ViewHolder的layout资源代码上,右键——>Generate——Generate ButterKnife Injections,然后就出现如图的选择框。

插件gitHub地址:https://github.com/avast/android-butterknife-zelezny

上面给了一个使用流程图,不过流程图不会针对最新的8.0.1版本的,但是都是差不多的

image

源码解析:

生成代码:注解本身不具有任何的作用,比如我们的 @Override 等.

Unbinder mUnbinder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutResource());
    mUnbinder = ButterKnife.bind(this);
}

返回一个Unbinder 对象

/**
   * BindView annotated fields and methods in the specified {@link Activity}. The current content
   * view is used as the view root.
   *
   * @param target Target activity for view binding.
   */
  @NonNull @UiThread
  public static Unbinder bind(@NonNull Activity target) {
    View sourceView = target.getWindow().getDecorView();
    return createBinding(target, sourceView);
  }

继续追踪createBinding:

  private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
    Class<?> targetClass = target.getClass();
    if (debug) Log.d(TAG, "Looking up binding for " + targetClass.getName());
    Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);

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

//noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
    try {
      return constructor.newInstance(target, source);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("Unable to invoke " + constructor, e);
    } catch (InstantiationException e) {
      throw new RuntimeException("Unable to invoke " + constructor, e);
    } catch (InvocationTargetException e) {
      Throwable cause = e.getCause();
      if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
      }
      if (cause instanceof Error) {
        throw (Error) cause;
      }
      throw new RuntimeException("Unable to create binding instance.", cause);
    }
  }

target.getClass()利用这个方法就可以获得一个实例的类型类,类型类指的是代表一个类型的类,因为一切皆是对象,类型也不例外,在Java使用类型类来表示一个类型。所有的类型类都是Class类的实例。

继续追踪findBindingConstructorForClass

@Nullable @CheckResult @UiThread
 private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
   Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
   if (bindingCtor != null) {
     if (debug) Log.d(TAG, "HIT: Cached in binding map.");
     return bindingCtor;
   }
   String clsName = cls.getName();
   if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
     if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search.");
     return null;
   }

   try {
     Class<?> bindingClass = Class.forName(clsName + "_ViewBinding");
     //noinspection unchecked
     bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class);
     if (debug) Log.d(TAG, "HIT: Loaded binding class and constructor.");
   } catch (ClassNotFoundException e) {
     if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName());
     bindingCtor = findBindingConstructorForClass(cls.getSuperclass());
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("Unable to find binding constructor for " + clsName, e);
   }
   BINDINGS.put(cls, bindingCtor);
   return bindingCtor;
 }

重点代码在:

 Class<?> bindingClass = Class.forName(clsName + "_ViewBinding");
  //noinspection unchecked
  bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class);

拿到需要注入的类 Class,拿到名称,然后在后面拼接上 _ViewBinding,然后根据这个名称寻找叫这个名称的 Class对象,也就是找到了这个类:包名+activityname__ViewBinding的class,找到了以后获取构造方法,并创建实例对象,也就是创建了我们的_ViewBinding 对象,

intermediates:是一个中间人,调节人的意思,
java源文件转为class文件后再转为dex文件,最后生成apk
这里面class文件夹就被存放在intermediates文件夹里面


image.png

生成的代码中,构造方法中就已经执行了控件注入和事件绑定的操作.所以一切都已经明了了.

所以对于ButterKnife框架的实现有两点是非常关键的:

编译时期根据注解中的信息,帮助我们生成一些必要的代码,这里就是会生成一个[你的类]_ViewBinding.java的类
在调用bind的时候,利用反射找到生成好的类来执行注入的过程.

1.在ButterKnife中由于生成的代码是和你的待绑定的类是一个包的,所以你使用注解的成员属性必须至少是包访问权限的,你不能写一个private 修饰的!
2.在调用bind的时候,利用反射找到生成好的类来执行注入的过程.这个过程我们在上面可以看到是利用反射实现的,并不是很多人口口相传的一点反射代码都没有的!
3.在调用绑定方法之后,会返回一个 Unbinder 对象,,我们从生成的代码中可以看到,每一个生成的代码的类都实现了 Unbinder 接口,就是为了销毁注入的成员变量用的.所以正确的使用姿势:

  @Override
protected void onDestroy() {
    super.onDestroy();
    if (unbinder != null) {
        unbinder.unbind();
    }
}

相关文章

网友评论

      本文标题:Android ButterKnife 笔记

      本文链接:https://www.haomeiwen.com/subject/cvzjvxtx.html