學習源碼-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閱讀 227,572評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內容

  • 前言 俗話說的好前人栽樹,后人乘涼,說實話,當我拿到源碼是,我確實不知道該從何看起。于是百度了各位先輩的源碼分析,...
    二十三歲的夢閱讀 375評論 0 0
  • 俗話說的好“不想偷懶的程序員,不是好程序員”,我們在日常開發android的過程中,在前端activity或者fr...
    蛋西閱讀 4,977評論 0 14
  • 前言 這個框架大家都是特別熟悉的了,JakeWharton大神的作品,項目地址,怎么用我就不多講了,可以去參考官方...
    foxleezh閱讀 1,420評論 0 7
  • 世界公認最高效的學習方法: 選擇一個你要學習的內容 想象如果你要將這些內容教授給一名新人,該如何講解 如果過程中出...
    斌林誠上閱讀 3,981評論 3 10
  • 博文出處:ButterKnife源碼分析,歡迎大家關注我的博客,謝謝! 0x01 前言 在程序開發的過程中,總會有...
    俞其榮閱讀 2,061評論 1 18