O3-開源框架使用之Butterknife 8.8.1及原始碼淺析

張風捷特烈發表於2018-11-07

零、前言

我最喜歡的框架,沒有之一:
編譯期生成程式碼的方式,對執行時沒有任何副作用。 加上AndroidStudio快捷鍵,簡直好用之至。

新增依賴:
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
複製程式碼
混淆
## butterknife start
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }

-keepclasseswithmembernames class * {
    @butterknife.* <fields>;
}

-keepclasseswithmembernames class * {
    @butterknife.* <methods>;
}
## butterknife end
複製程式碼

一、Activity中使用

1.基礎使用:
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.id_tv)
    TextView mIdTv;//繫結檢視
    @BindView(R.id.id_btn)
    Button mIdBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.繫結Activity
        ButterKnife.bind(this);
    }

    @OnClick(R.id.id_btn)//單機事件
    public void onViewClicked() {
        Log.e(TAG, "onViewClicked: ");
    }

    @OnLongClick(R.id.id_btn)//長按事件
    public boolean onViewLongClicked() {
        Log.e(TAG, "onViewLongClicked: ");

        //和原生一樣,返回true,抬起時不觸發單機
        return true;
    }
}

複製程式碼
多事件:
@OnClick({R.id.id_btn, R.id.imageView})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.id_btn:
            break;
        case R.id.imageView:
            break;
    }
}
複製程式碼

二、Fragment中使用:

public class MyFragment extends Fragment {

    @BindView(R.id.imageView)
    ImageView mImageView;
    Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_test, container, false);
        //繫結View
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //銷燬時解綁View
    @OnClick(R.id.imageView)
    public void onViewClicked() {
        Toast.makeText(getContext(), "hello", Toast.LENGTH_LONG).show();
    }
}
複製程式碼

附:使用Fragment

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.id_fl,new MyFragment());
ft.commit();
複製程式碼

還有其他很多註解,感覺都沒用太大用,下面看一下原始碼是怎麼工作的


三、原始碼淺析:

1、首先來看這句話都進行了哪些事:ButterKnife.bind(this);

---B0:butterknife.ButterKnife#bind(android.app.Activity)

bind有6個過載的方法:這裡使用的是一參Activity的bind方法

  @NonNull @UiThread
  public static Unbinder bind(@NonNull Activity target) {
  //獲取Activity對應視窗上的最頂端佈局
    View sourceView = target.getWindow().getDecorView();
    //呼叫createBinding方法,見--B1
    return createBinding(target, sourceView);
  }
複製程式碼
--B1:butterknife.ButterKnife#createBinding

這算一個非常核心的方法,6個bind()方法都是呼叫它

private static Unbinder createBinding(@NonNull Object target, @NonNull View source) {
    //獲取target的class
    Class<?> targetClass = target.getClass();
    if (debug) Log.d(TAG, "Looking up binding for " + targetClass.getName());
    //獲取繫結Class的建構函式,見--B2
    Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
    //如果建構函式是空的,返回EMPTY的Unbinder列舉
    if (constructor == null) {
      return Unbinder.EMPTY;
    }

    //noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
    try {
    //返回使用建構函式建立MainActivity_ViewBinding例項:
      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);
    }
  }
複製程式碼
--B2:butterknife.ButterKnife#findBindingConstructorForClass

通過位元組碼檔案獲取類的建構函式

 @Nullable @CheckResult @UiThread
  private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) {
  
  //BINDINGS的宣告:可見是一個LinkedHashMap,以class為鍵,建構函式為值。
  //static final Map<Class<?>, Constructor<? extends Unbinder>> BINDINGS = new LinkedHashMap<>();
    //從map中拿傳入的cls的建構函式
    Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls);
    //如果不為空
    if (bindingCtor != null) {
      if (debug) Log.d(TAG, "HIT: Cached in binding map.");
      //就返回拿到的建構函式
      return bindingCtor;
    }
    //否則,獲取位元組碼檔案的名字:如:com.toly1994.butterknifetest.MainActivity
    String clsName = cls.getName();
    //如果名字的字串,是以android.或java.開頭的
    if (clsName.startsWith("android.") || clsName.startsWith("java.")) {
      if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search.");
      //返回空
      return null;
    }
    try {
    //載入com.toly1994.butterknifetest.MainActivity_ViewBinding類生成Clazz物件bindingClass:見:--B3
      Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");
      //noinspection unchecked
      //獲取自動生成的MainActivity_ViewBinding中的兩參建構函式
      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);
    }
    //將cls和獲取到的建構函式放入map
    BINDINGS.put(cls, bindingCtor);
    return bindingCtor;
  }
複製程式碼
--B3:見鬼,哪來的什麼MainActivity_ViewBinding讓我載入?

Butter Knife會自動建立這個類,我們來看看它的廬山真面目

MainActivity_ViewBinding.png

可見bind方法,主要是把XxxActivity建立一個XxxActivity_ViewBinding,並建立一個XxxActivity_ViewBinding物件


2、現在焦點就在MainActivity_ViewBinding的身上

com.toly1994.butterknifetest.MainActivity_ViewBinding
// Generated code from Butter Knife. Do not modify!

public class MainActivity_ViewBinding implements Unbinder {
//持有一個MainActivity的引用
  private MainActivity target;
//持有一個View的引用
  private View view2131165244;

//一參構造:呼叫兩參構造
  @UiThread
  public MainActivity_ViewBinding(MainActivity target) {
    this(target, target.getWindow().getDecorView());
  }
  
//兩參構造:
  @UiThread
  public MainActivity_ViewBinding(final MainActivity target, View source) {
 //target賦值
    this.target = target;
    View view;
    //將target物件中的mIdTv賦值為:findRequiredViewAsType(檢視,id,欄位介紹,類名)方法:見--B4
    target.mIdTv = Utils.findRequiredViewAsType(source, R.id.id_tv, "field 'mIdTv'", TextView.class);
    //findRequiredView找到按鈕,見:--B4-1
    view = Utils.findRequiredView(source, R.id.id_btn, "field 'mIdBtn' and method 'onViewClicked'");
    //view強轉後為target物件中的mIdBtn賦值
    target.mIdBtn = Utils.castView(view, R.id.id_btn, "field 'mIdBtn'", Button.class);
    view2131165244 = view;
    //為按鈕設定監聽:見--B5
    view.setOnClickListener(new DebouncingOnClickListener() {
      @Override
      public void doClick(View p0) {
      //這裡是呼叫的target也就是Activity中的onViewClicked方法
      //應該知道為什麼可以簡便的寫點選事件了吧
        target.onViewClicked();
      }
    });
  }

  @Override
  @CallSuper
  //解綁:置空操作
  public void unbind() {
    MainActivity target = this.target;
    if (target == null) throw new IllegalStateException("Bindings already cleared.");
    this.target = null;
    target.mIdTv = null;
    target.mIdBtn = null;
    view2131165244.setOnClickListener(null);
    view2131165244 = null;
  }
}

複製程式碼
--B4:butterknife.internal.Utils#findRequiredViewAsType

根據型別查詢需要的View
這個who只是在拋異常的時候告訴你,是誰異常

  public static <T> T findRequiredViewAsType(View source, @IdRes int id, String who,
      Class<T> cls) {
     //findRequiredView(檢視,id,欄位介紹):見--B4-1
    View view = findRequiredView(source, id, who);
    //castView(檢視,id,欄位, Class):見--B4-2
    return castView(view, id, who, cls);
  }
複製程式碼
--B4-1:findRequiredView(檢視,id,欄位介紹)

看到findViewById有沒有小激動

  public static View findRequiredView(View source, @IdRes int id, String who) {
  //真正的findViewById操作
    View view = source.findViewById(id);
    if (view != null) {
    //如果檢視不為空就返回找到的檢視
      return view;
    }
    //檢視為空,就丟擲一個IllegalStateException異常:
    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'"
    
複製程式碼
--B4-2:castView(檢視,id,欄位, Class)
public static <T> T castView(View view, @IdRes int id, String who, Class<T> cls) {
  try {
  //將View強轉為T型別,T型別是Class<T>中的泛型,即findRequiredViewAsType中傳入的型別
    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);
  }
}
複製程式碼

cast()方法是Clazz的一個公共方法:由下可見它反會一個由傳入值強轉成的T型別物件

    @SuppressWarnings("unchecked")
    public T cast(Object obj) {
        if (obj != null && !isInstance(obj))
            throw new ClassCastException(cannotCastMsg(obj));
        return (T) obj;
    }
複製程式碼
--B5:這是butterknife原始碼中的一個類:

繼承自:View.OnClickListener

public abstract class DebouncingOnClickListener implements View.OnClickListener {
//是否可用
  static boolean enabled = true;

//可以再次使用
  private static final Runnable ENABLE_AGAIN = new Runnable() {
    @Override public void run() {
      enabled = true;
    }
  };

  @Override public final void onClick(View v) {
  //如果可用
    if (enabled) {
    //設定為不可用
      enabled = false;
      //
      v.post(ENABLE_AGAIN);
      doClick(v);//模板方法
    }
  }

  public abstract void doClick(View v);
}

複製程式碼

後記、

1.宣告:

[1]本文由張風捷特烈原創,轉載請註明
[2]歡迎廣大程式設計愛好者共同交流
[3]個人能力有限,如有不正之處歡迎大家批評指證,必定虛心改正
[4]你的喜歡與支援將是我最大的動力

2.連線傳送門:

更多安卓技術歡迎訪問:安卓技術棧
我的github地址:歡迎star
簡書首發,騰訊雲+社群同步更新
張風捷特烈個人網站,程式設計筆記請訪問:www.toly1994.com

3.聯絡我

QQ:1981462002
郵箱:1981462002@qq.com
微信:zdl1994328

4.歡迎關注我的微信公眾號,最新精彩文章,及時送達:

公眾號.jpg

相關文章