学习源码-ButterKnife

如何使用

添加依赖

    implementation "com.jakewharton:butterknife:$butterKnifeVersion"
    annotationProcessor "com.jakewharton:butterknife-compiler:$butterKnifeVersion"

在Activity中使用

声明Unbinder对象为局部变量

    private Unbinder mUnbinder;

ActivityonCreate生命周期中初始化mUnbinder

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

@BindView注解绑定view_id给你对应的view

    @BindView(R.id.tv_date)
    TextView tvDate;

当你view较多的时候需要你多次编写类似的代码,比较耗时,此时可以使用Android ButterKnife Zelezny插件。
如何添加插件?

添加插件

点击File打开菜单

点击File打开菜单

点击Settings...打开设置页面
点击Settings...打开设置页面

点击Plugins打开插件设置页面,选择Marketplace标签页
点击Plugins打开插件设置页面,选择Marketplace标签页

在搜索栏中输入ButterKnife后,按回车确认,点击第一个插件下的INSTALL安装,安装完成后重启AndroidStudio
在搜索栏中输入ButterKnife后,按回车确认

使用插件

重启完成后打开你需要使用@BindViewActivity页面,在布局文件的id上单击右键,然后选择Generate...菜单

单击右键.jpg

在弹出的菜单中选择Generate Butterknife Injections
选择最下方Generate Butterknife Injections

在之后的菜单中,勾选你需要在Activity中创建的view,然后点击CONFIRM,就会自动生成对应的@BindView代码
勾选菜单生成对应代码

除了这些代码,还会额外在onDestory方法中生成mUnbinder的解绑代码,是我们使用ButterKnife必要的代码

    if (mUnbinder != null) {
        mUnbinder.unbind();
    }

以上就是在Activity中使用时的简单步骤

学习源码

查看学习Unbinder对象源码

    import android.support.annotation.UiThread;

    /** An unbinder contract that will unbind views when called. */
    public interface Unbinder {
        @UiThread void unbind();

        Unbinder EMPTY = new Unbinder() {
          @Override public void unbind() { }
        };
    }

其中包含了一个在UiThread中执行的unbind()方法,以及一个初始化好的EMPTYUnbinder实例。

接下来查看学习ButterKnife.bind(this)bind方法。

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

这段代码获取了Activity的顶层视图,并作为参数传入了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);
    }
  }

这个方法再第四行代码中通过findBindingConstructorForClass(targetClass)方法获取到一个Constructor<? extends Unbinder>实例,余下的都是一些异常处理,那么我们就需要继续深入findBindingConstructorForClass(targetClass)一探究竟。

  @Nullable @CheckResult @UiThread
  private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
    Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
    //BINDINGS
    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 = cls.getClassLoader().loadClass(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;
  }

这里是实例化BINDINGS的代码,它是一个LinkedHashMap,用来缓存已经匹配到过的bindingCtor以节省开销。
可以看到上面的代码中倒数第二行,将匹配到的bindingCtor放入了BINDINGS中。

  @VisibleForTesting
  static final Map<Class<?>, Constructor<? extends Unbinder>> BINDINGS = new LinkedHashMap<>();

那么对我们来说有意义的代码就是try catch代码块中的内容了

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

clsName是你传进来的Activity的名字,以我传入的为例与后面的拼接之后就是MainActivity_ViewBinding。我们全局搜索一下这个类名。

MainActivity_ViewBinding

这是我们编译代码之后生成的辅助文件。那么findBindingConstructorForClass这个方法返回的就是通过反射得到的MainActivity_ViewBinding的构造方法。然后在createBinding方法中使用constructor.newInstance(target, source)得到了MainActivity_viewBinding的实例。
至此,我们已经了解了ButterKnife.bind(this)这个方法所做的工作。

接下来我们仔细查看这个生成的类帮我们做了什么。

    target.vStatusBg = Utils.findRequiredView(source, R.id.v_status_bg, "field 'vStatusBg'");
    
    target.tvDate = Utils.findRequiredViewAsType(source, R.id.tv_date, "field 'tvDate'", TextView.class);

    target.tvMenuBuyCarService = Utils.castView(view, R.id.tv_menu_buy_car_service, "field 'tvMenuBuyCarService'", TextView.class);

我们查看MainActivity_ViewBinding类源码之后,看到,给对应的view赋值的方法有这三个。接下来我们继续查看这三个方法。

  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.");
  }

  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 <T> T castView(View view, @IdRes int id, String who, Class<T> 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);
    }
  }

我们可以看到最终还是通过findViewByIdview赋值

到这里我们将简单的BindView的流程走完了,我们发现最重要的步骤其实应该是MainActivity_ViewBinding这个类的生成,它代替我们做了一系列findViewById的工作。

那我们会有一个疑问MainActivity_ViewBinding这个类是怎么生成的呢?
我们打开这个文件查看路径

Mainactivity_ViewBinding路径

当看到apt时,我们搜一下apt是什么:APT(Annotation Processing Tool)即注解处理器,是一种处理注解的工具,确切的说它是javac的一个工具,它用来在编译时扫描和处理注解。注解处理器以Java代码(或者编译过的字节码)作为输入,生成.java文件作为输出。
简单来说就是在编译期,通过注解生成.java文件。

我们在添加ButterKnife依赖的时候还添加了这样一行代码annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.butterKnifeVersion"

接下来我们通过github下载得到butterknife的源码。

Butterknife源码

我们看到了我们所引用的butterknife-compiler项目,我们在下一篇来一探究竟。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • 前言 俗话说的好前人栽树,后人乘凉,说实话,当我拿到源码是,我确实不知道该从何看起。于是百度了各位先辈的源码分析,...
    二十三岁的梦阅读 345评论 0 0
  • 俗话说的好“不想偷懒的程序员,不是好程序员”,我们在日常开发android的过程中,在前端activity或者fr...
    蛋西阅读 4,959评论 0 14
  • 前言 这个框架大家都是特别熟悉的了,JakeWharton大神的作品,项目地址,怎么用我就不多讲了,可以去参考官方...
    foxleezh阅读 1,404评论 0 7
  • 世界公认最高效的学习方法: 选择一个你要学习的内容 想象如果你要将这些内容教授给一名新人,该如何讲解 如果过程中出...
    斌林诚上阅读 3,967评论 3 10
  • 博文出处:ButterKnife源码分析,欢迎大家关注我的博客,谢谢! 0x01 前言 在程序开发的过程中,总会有...
    俞其荣阅读 2,019评论 1 18