編輯:關於 Android 程式設計
前兩篇我們分析到處理器的 findAndParseTargets 方法,它會把使用注解的類的 TypeElement 與解析後的 BindingClass 組裝成一個集合。本篇接著看處理器的核心方法 process。
@Override public boolean process(Set elements, RoundEnvironment env) { Map targetClassMap = findAndParseTargets(env); for (Map.Entry entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); BindingClass bindingClass = entry.getValue(); JavaFile javaFile = bindingClass.brewJava(); try { javaFile.writeTo(filer); } catch (IOException e) { error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage()); } } return true; } 先來看 BindingClass 的一些關鍵集合成員變量:
// @BindView 解析後形成的 ViewBindings 集合 private final MapviewIdMap = new LinkedHashMap<>(); // @BindViews 解析後形成的集合,如 @BindViews({ R2.id.title, R2.id.subtitle }) List headerViews; private final Map > collectionBindings = new LinkedHashMap<>(); // @BindBitmap 解析後形成的集合 private final List bitmapBindings = new ArrayList<>(); // @BindDrawable 解析後形成的集合 private final List drawableBindings = new ArrayList<>(); // @BindFloat、@BindInt、@BindString 等解析後形成的集合 private final List resourceBindings = new ArrayList<>();
類似的 add 方法如下:
void addFieldCollection(Listids, FieldCollectionViewBinding binding) { collectionBindings.put(binding, ids); } boolean addMethod(Id id, ListenerClass listener, ListenerMethod method, MethodViewBinding binding) { ViewBindings viewBindings = getOrCreateViewBindings(id); if (viewBindings.hasMethodBinding(listener, method) && !"void".equals(method.returnType())) { return false; } viewBindings.addMethodBinding(listener, method, binding); return true; } void addResource(FieldResourceBinding binding) { resourceBindings.add(binding); }
至此,所有注解與方法都被放進了集合,生成 java 文件時只需遍歷這些集合即可。以官方 demo 的 SimpleActivity 為例,編譯後生成的是 SimpleActivity_ViewBinding,離目標越來越近了。
生成 java 文件固然可以用字符串拼接,但 Jake 大神並沒有這麼做,而是自己寫了一個庫——javapoet:

compile 'com.squareup:javapoet:1.7.0'
它能很方便地生成我們想要的 java 文件。process 方法中遍歷 targetClassMap,調用每個類的 brewJava() 返回 JavaFile,再通過 writeTo 寫出文件。
JavaFile brewJava() { // 參數1:包名;參數2:TypeSpec,可生成 class、interface 等 return JavaFile.builder(bindingClassName.packageName(), createBindingClass()) .addFileComment("Generated code from Butter Knife. Do not modify!") .build(); }可以看到 javapoet 採用了 builder 設計模式,值得細細品味。主要分三步:生成類名、生成構造函數、生成 unbind 方法。
private TypeSpec createBindingClass() { // 1. 生成類名 TypeSpec.Builder result = TypeSpec.classBuilder(bindingClassName.simpleName()) .addModifiers(PUBLIC); TypeName targetType; if (isFinal) { result.addModifiers(FINAL); targetType = targetTypeName; } else { targetType = TypeVariableName.get("T"); result.addTypeVariable(TypeVariableName.get("T", targetTypeName)); } if (hasParentBinding()) { result.superclass(ParameterizedTypeName.get(getParentBinding(), targetType)); } else { result.addSuperinterface(UNBINDER); result.addField(targetType, "target", isFinal ? PRIVATE : PROTECTED); } // 2. 生成構造函數 if (!bindNeedsView()) { result.addMethod(createBindingViewDelegateConstructor(targetType)); } result.addMethod(createBindingConstructor(targetType)); // 3. 生成 unbind 方法 if (hasViewBindings() || !hasParentBinding()) { result.addMethod(createBindingUnbindMethod(result, targetType)); } return result.build(); }類名即 xxx_ViewBinding。若在 Activity 中,生成的類為 public、實現 Unbinder 接口並帶泛型;若在 ViewHolder 中,則為 final 類並持有具體 target。
核心是 createBindingConstructor 方法,主要做成員賦值與設置監聽。先了解 javapoet 提供的 MethodSpec:
MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addAnnotation(UI_THREAD) .addModifiers(PUBLIC); constructor.addParameter(targetType, "target"); constructor.addStatement("this.target = target");addStatement 的第一個參數是帶占位符(S 表示字符串、T 表示類型等)的模板,後面是可變參數,用法類似 String.format()。
變量賦值主要調用系統的 findViewById。你會看到 findRequiredViewAsType、findRequiredView、castView 等封裝方法,它們最終都會走到 findViewById:
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."); }castView 則是 Class 的方法,直接把 View 轉為指定類型。注意 target.title 中的 target 就是 Activity 或 View,這也解釋了為什麼 @BindView 的字段不能是 private。
接著是 addMethodBindings 設置監聽,同樣借助 MethodSpec.methodBuilder 循環添加:
for (ListenerMethod method : getListenerMethods(listener)) { MethodSpec.Builder callbackMethod = MethodSpec.methodBuilder(method.name()) .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(bestGuess(method.returnType())); String[] parameterTypes = method.parameters(); for (int i = 0, count = parameterTypes.length; i < count; i++) { callbackMethod.addParameter(bestGuess(parameterTypes[i]), "p" + i); } }最終生成的構造函數類似:
@UiThread public SimpleActivity_ViewBinding(final T target, View source) { this.target = target; View view; target.title = Utils.findRequiredViewAsType(source, R.id.title, "field 'title'", TextView.class); target.subtitle = Utils.findRequiredViewAsType(source, R.id.subtitle, "field 'subtitle'", TextView.class); view = Utils.findRequiredView(source, R.id.hello, "field 'hello', method 'sayHello', and method 'sayGetOffMe'"); target.hello = Utils.castView(view, R.id.hello, "field 'hello'", Button.class); view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.sayHello(); } }); view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View p0) { return target.sayGetOffMe(); } }); } createBindingUnbindMethod 主要把成員變量、Listener 置空,例如 setOnClickListener(null),幫助 GC 及時回收內存。
private MethodSpec createBindingUnbindMethod(TypeSpec.Builder bindingClass, TypeName targetType) { MethodSpec.Builder result = MethodSpec.methodBuilder("unbind") .addAnnotation(Override.class) .addModifiers(PUBLIC); if (!isFinal && !hasParentBinding()) { result.addAnnotation(CALL_SUPER); } boolean rootBindingWithFields = !hasParentBinding() && hasFieldBindings(); if (hasFieldBindings() || rootBindingWithFields) { result.addStatement("$T target = this.target", targetType); } if (!hasParentBinding()) { String target = rootBindingWithFields ? "target" : "this.target"; result.addStatement("if ($N == null) throw new $T($S)", target, IllegalStateException.class, "Bindings already cleared."); } else { result.addStatement("super.unbind()"); } if (hasFieldBindings()) { for (ViewBindings bindings : viewIdMap.values()) { if (bindings.getFieldBinding() != null) { result.addStatement("target.$L = null", bindings.getFieldBinding().getName()); } } } if (!hasParentBinding()) { result.addStatement("this.target = null"); } return result.build(); }addStatement 的用法與前面一致,生成的方法類似:
@Override public void unbind() { SimpleAdapter.ViewHolder target = this.target; if (target == null) throw new IllegalStateException("Bindings already cleared."); target.word = null; target.length = null; target.position = null; this.target = null; }
Android 繪製太極圖實例
太極圖是常見的圖形繪製案例,很適合用來練習 Canvas 與 Paint。透過圓弧、半圓與小圓的組合,可以用純程式碼畫出黑白雙魚。 繪製步驟 先畫出外圈,將圓分成黑白
Android 自訂控件系列:從源碼理解 View 的顯示與滾動
我們在 Android 設備上所看到的畫面,其實與底層的繪製機制關係密切。本文從源碼出發,帶你理解 View 是如何被繪製,以及它又是如何控制顯示位置的。 理解 View
Android 懸浮相機窗口實戰:WindowManager + Service + Camera 全流程
懸浮窗裡嵌一個相機預覽,是很多工具類應用的常見需求,比如掃碼懸浮入口、遠程監控小窗、拍照打卡等。本文把這個功能的完整鏈路走一遍:用 WindowManager 把一個極小
Android ActionBar 實作:以「下拉清單」作為導航模式
上一篇我們聊過 ActionBar 是 Android 3.0 的重要更新之一。這篇直接動手,寫一個開發中很常用的場景——用 ActionBar 實作基於下拉清單的導航。