編輯:關於 Android 程式設計
接續上一篇,我們從 parseBindView 的步驟 3 往下看。
BindingClass bindingClass = targetClassMap.get(enclosingElement);
if (bindingClass != null) {
ViewBindings viewBindings = bindingClass.getViewBinding(getId(id));
if (viewBindings != null && viewBindings.getFieldBinding() != null) {
FieldViewBinding existingBinding = viewBindings.getFieldBinding();
error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
BindView.class.getSimpleName(), id,
existingBinding.getName(),
enclosingElement.getQualifiedName(),
element.getSimpleName());
return;
}
} else {
bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
}
邏輯很直白:
1. 若 map(快取)中已有對應的 BindingClass,就依 id 取出其中的 ViewBindings 實例。若 viewBindings 不為空且其 FieldBinding 不為空,代表同一個 id 被 bind 了兩次,直接拋出錯誤。
2. 若為空,則呼叫 getOrCreateTargetClass 取得或建立,參數是最初的 map 與父節點。
private BindingClass getOrCreateTargetClass(
Map<TypeElement, BindingClass> targetClassMap,
TypeElement enclosingElement) {
BindingClass bindingClass = targetClassMap.get(enclosingElement);
if (bindingClass == null) {
// 取得父節點的型別名稱
TypeName targetType = TypeName.get(enclosingElement.asType());
if (targetType instanceof ParameterizedTypeName) {
targetType = ((ParameterizedTypeName) targetType).rawType;
}
// 取得該節點所在的套件名稱
String packageName = getPackageName(enclosingElement);
// 類別名稱
String className = getClassName(enclosingElement, packageName);
// 組出 bindingClassName,並加上 _ViewBinding 後綴
ClassName bindingClassName =
ClassName.get(packageName, className + "_ViewBinding");
// 是否為 final 類別
boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL);
// 建立 BindingClass 實例
bindingClass = new BindingClass(targetType, bindingClassName, isFinal);
// 放入集合做快取
targetClassMap.put(enclosingElement, bindingClass);
}
return bindingClass;
}
這裡可以看到,最終要生成的類別名稱就是「原類名 + _ViewBinding」。
//@BindView(R.id.word)
//TextView word;
// name 即為 word
String name = element.getSimpleName().toString();
// 欄位型別名稱
TypeName type = TypeName.get(elementType);
// 是否要求可為空
boolean required = isFieldRequired(element);
// 建立 FieldViewBinding 實例
FieldViewBinding binding = new FieldViewBinding(name, type, required);
// 加入 bindingClass 的成員變數集合,供後續生成 java 原始碼時使用
bindingClass.addField(getId(id), binding);
其他幾種成員變數註解(如 @BindViews)流程大同小異。至此,查找並解析成員變數的流程全部結束,接下來進入事件監聽的處理。
回到 findAndParseTargets 方法:
// ... 省略成員變數的註解處理
// 逐一處理對應到 listener 的註解
for (Class<? extends Annotation> listener : LISTENERS) {
findAndParseListener(env, listener, targetClassMap, erasedTargetNames);
}
// 嘗試為每個類別找出父類別綁定器
for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
TypeElement parentType = findParentType(entry.getKey(), erasedTargetNames);
if (parentType != null) {
BindingClass bindingClass = entry.getValue();
BindingClass parentBindingClass = targetClassMap.get(parentType);
bindingClass.setParent(parentBindingClass);
}
}
return targetClassMap;
事件處理同样分為「查找」與「解析」兩大步。LISTENERS 是 ButterKnife 支援的註解集合:
private static final List<Class<? extends Annotation>> LISTENERS = Arrays.asList(
// OnCheckedChanged.class,
// OnClick.class,
// OnEditorAction.class,
// OnFocusChange.class,
// OnItemClick.class,
// OnItemLongClick.class,
// OnItemSelected.class,
// OnLongClick.class,
// OnPageChange.class,
// OnTextChanged.class,
// OnTouch.class
);
private void findAndParseListener(RoundEnvironment env,
Class<? extends Annotation> annotationClass,
Map<TypeElement, BindingClass> targetClassMap,
Set<TypeElement> erasedTargetNames) {
for (Element element : env.getElementsAnnotatedWith(annotationClass)) {
// 檢查合法性
if (!SuperficialValidation.validateElement(element)) continue;
try {
parseListenerAnnotation(annotationClass, element,
targetClassMap, erasedTargetNames);
} catch (Exception e) {
StringWriter stackTrace = new StringWriter();
e.printStackTrace(new PrintWriter(stackTrace));
error(element, "Unable to generate view binder for @%s.\n\n%s",
annotationClass.getSimpleName(), stackTrace.toString());
}
}
}
private void parseListenerAnnotation(Class<? extends Annotation> annotationClass,
Element element,
Map<TypeElement, BindingClass> targetClassMap,
Set<TypeElement> erasedTargetNames) throws Exception {
// 註解只能標在方法上
if (!(element instanceof ExecutableElement) || element.getKind() != METHOD) {
throw new IllegalStateException(String.format(
"@%s annotation must be on a method.", annotationClass.getSimpleName()));
}
ExecutableElement executableElement = (ExecutableElement) element;
// 取得父節點
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// 取得該方法的註解
Annotation annotation = element.getAnnotation(annotationClass);
// 每個 listener 註解都有 value(),且為 int 陣列
// 之所以是陣列,是為了支援 @OnClick({R.id.hello, R.id.hello2})
Method annotationValue = annotationClass.getDeclaredMethod("value");
if (annotationValue.getReturnType() != int[].class) {
throw new IllegalStateException(String.format(
"@%s annotation value() type not int[].", annotationClass));
}
int[] ids = (int[]) annotationValue.invoke(annotation);
String name = executableElement.getSimpleName().toString();
boolean required = isListenerRequired(executableElement);
// 檢查方法與所屬類別是否可從生成碼存取
boolean hasError = isInaccessibleViaGeneratedCode(annotationClass, "methods", element);
hasError |= isBindingInWrongPackage(annotationClass, element);
// 同一個註解中不能出現重複 id
Integer duplicateId = findDuplicate(ids);
if (duplicateId != null) {
error(element, "@%s annotation for method contains duplicate ID %d. (%s.%s)",
annotationClass.getSimpleName(), duplicateId,
enclosingElement.getQualifiedName(), element.getSimpleName());
hasError = true;
}
// 取得 listener 類別上的 @ListenerClass 註解
ListenerClass listener = annotationClass.getAnnotation(ListenerClass.class);
if (listener == null) {
throw new IllegalStateException(String.format("No @%s defined on @%s.",
ListenerClass.class.getSimpleName(), annotationClass.getSimpleName()));
}
// 檢查 id 合法性(NO_ID 為 -1)
for (int id : ids) {
if (id == NO_ID.value) {
if (ids.length == 1) {
// 無 id 的綁定不得使用 @Optional
if (!required) {
error(element,
"ID-free binding must not be annotated with @Optional. (%s.%s)",
enclosingElement.getQualifiedName(), element.getSimpleName());
hasError = true;
}
} else {
error(element, "@%s annotation contains invalid ID %d. (%s.%s)",
annotationClass.getSimpleName(), id,
enclosingElement.getQualifiedName(), element.getSimpleName());
hasError = true;
}
}
}
// 取得要實作的方法資訊
ListenerMethod method;
ListenerMethod[] methods = listener.method();
if (methods.length > 1) {
throw new IllegalStateException(String.format(
"Multiple listener methods specified on @%s.",
annotationClass.getSimpleName()));
} else if (methods.length == 1) {
// 使用 method() 時,callbacks() 必須為空,兩者互斥
if (listener.callbacks() != ListenerClass.NONE.class) {
throw new IllegalStateException(String.format(
"Both method() and callback() defined on @%s.",
annotationClass.getSimpleName()));
}
method = methods[0];
} else {
// 否則改用 callback
Method annotationCallback = annotationClass.getDeclaredMethod("callback");
Enum<?> callback = (Enum<?>) annotationCallback.invoke(annotation);
Field callbackField = callback.getDeclaringClass().getField(callback.name());
method = callbackField.getAnnotation(ListenerMethod.class);
if (method == null) {
throw new IllegalStateException(String.format(
"No @%s defined on @%s's %s.%s.",
ListenerMethod.class.getSimpleName(), annotationClass.getSimpleName(),
callback.getDeclaringClass().getSimpleName(), callback.name()));
}
}
// 驗證參數個數:不可多於 listener 定義的參數數量
List<? extends VariableElement> methodParameters = executableElement.getParameters();
if (methodParameters.size() > method.parameters().length) {
error(element, "@%s methods can have at most %s parameter(s). (%s.%s)",
annotationClass.getSimpleName(), method.parameters().length,
enclosingElement.getQualifiedName(), element.getSimpleName());
hasError = true;
}
// 驗證回傳型別
TypeMirror returnType = executableElement.getReturnType();
if (returnType instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) returnType;
returnType = typeVariable.getUpperBound();
}
if (!returnType.toString().equals(method.returnType())) {
error(element, "@%s methods must have a '%s' return type. (%s.%s)",
annotationClass.getSimpleName(), method.returnType(),
enclosingElement.getQualifiedName(), element.getSimpleName());
hasError = true;
}
if (hasError) {
return;
}
// 逐一比對參數型別,找出每個參數對應到 listener 的第幾個參數
Parameter[] parameters = Parameter.NONE;
if (!methodParameters.isEmpty()) {
parameters = new Parameter[methodParameters.size()];
BitSet methodParameterUsed = new BitSet(methodParameters.size());
String[] parameterTypes = method.parameters();
for (int i = 0; i < methodParameters.size(); i++) {
VariableElement methodParameter = methodParameters.get(i);
TypeMirror methodParameterType = methodParameter.asType();
if (methodParameterType instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) methodParameterType;
methodParameterType = typeVariable.getUpperBound();
}
for (int j = 0; j < parameterTypes.length; j++) {
if (methodParameterUsed.get(j)) {
continue;
}
if (isSubtypeOfType(methodParameterType, parameterTypes[j])
|| isInterface(methodParameterType)) {
parameters[i] = new Parameter(j, TypeName.get(methodParameterType));
methodParameterUsed.set(j);
break;
}
}
if (parameters[i] == null) {
// 組出詳細的錯誤訊息,提示所有合法的參數清單
StringBuilder builder = new StringBuilder();
builder.append("Unable to match @")
.append(annotationClass.getSimpleName())
.append(" method arguments. (")
.append(enclosingElement.getQualifiedName())
.append('.')
.append(element.getSimpleName())
.append(')');
for (int j = 0; j < parameters.length; j++) {
Parameter parameter = parameters[j];
builder.append("\n\n Parameter #").append(j + 1).append(": ")
.append(methodParameters.get(j).asType().toString())
.append("\n ");
if (parameter == null) {
builder.append("did not match any listener parameters");
} else {
builder.append("matched listener parameter #")
.append(parameter.getListenerPosition() + 1)
.append(": ")
.append(parameter.getType());
}
}
builder.append("\n\nMethods may have up to ")
.append(method.parameters().length).append(" parameter(s):\n");
for (String parameterType : method.parameters()) {
builder.append("\n ").append(parameterType);
}
builder.append("\n\nThese may be listed in any order but will be "
+ "searched for from top to bottom.");
error(executableElement, builder.toString());
return;
}
}
}
// 建立方法的 Binding 實體
MethodViewBinding binding = new MethodViewBinding(name, Arrays.asList(parameters), required);
// 取得或建立 BindingClass
BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
for (int id : ids) {
// 把方法加入 bindingClass 的方法集合,一切都是为了生成 java 程式碼
if (!bindingClass.addMethod(getId(id), listener, method, binding)) {
error(element,
"Multiple listener methods with return value specified for ID %d. (%s.%s)",
id, enclosingElement.getQualifiedName(), element.getSimpleName());
return;
}
}
erasedTargetNames.add(enclosingElement);
}
先看 OnItemClick 的定義:
@Target(METHOD)
@Retention(CLASS)
@ListenerClass(
targetType = "android.widget.AdapterView<?>",
setter = "setOnItemClickListener",
type = "android.widget.AdapterView.OnItemClickListener",
method = @ListenerMethod(
name = "onItemClick",
parameters = {
"android.widget.AdapterView<?>",
"android.view.View",
"int",
"long"
}
)
)
public @interface OnItemClick {
/** 要綁定此方法的所有 View ID */
@IdRes int[] value() default { View.NO_ID };
}
再看 ListenerClass:
@Retention(RUNTIME)
@Target(ANNOTATION_TYPE)
public @interface ListenerClass {
String targetType();
/** 在 targetType 上設定 listener 的 setter 方法名稱 */
String setter();
/** 移除 listener 的方法名稱,留空則沿用 setter() */
String remover() default "";
/** listener 介面的完整類名 */
String type();
/** 列舉 listener 的 callback 方法,與 method() 互斥 */
Class<? extends Enum<?>> callbacks() default NONE.class;
/** 單方法 listener 的方法資訊,與 callbacks() 互斥 */
ListenerMethod[] method() default { };
/** callbacks() 的預設值 */
enum NONE { }
}
以及 ListenerMethod:
@Retention(RUNTIME)
@Target(FIELD)
public @interface ListenerMethod {
/** 此方法註解所對應的 listener 方法名稱 */
String name();
/** 參數型別清單,非 primitive 者須為完整限定名 */
String[] parameters() default { };
/** listener 方法的回傳型別,亦可能為 void */
String returnType() default "void";
/** 若 returnType() 不是 void,未綁定時回傳的預設值 */
String defaultReturn() default "null";
}
把這三者一起看就很清楚了:ListenerMethod 描述「要實作哪個方法、參數與回傳型別」;ListenerClass 描述「要呼叫哪個 setter、listener 介面在哪裡」;而 OnItemClick 上填的值,正是我們平常在程式碼中設定的那些。
至此,findAndParseTargets 的流程就走完了。細節雖多,但正是這些細節決定了框架的健壯性——反覆推敲大神的實作,收穫往往比單純使用 API 來得更多。
源碼剖析 ImageView 的 ScaleType:八種縮放模式的真實行為
做 Android 開發的人對系統控制項都不陌生,Button、TextView、ImageView 幾乎天天在用。但要說 ImageView 的用法,多數人的答案僅止於
安卓手機怎麼重裝系統?兩種刷機方式圖文完整教學
我們常聽說電腦要重裝系統,那智慧型手機呢?其實手機也可以,只是我們通常稱之為「刷機」。本文以刷機工具「卓大師」為例,示範兩種最常見的做法。 先說明一個關鍵差異:與電腦不同
ListView 裡跑倒計時如何不卡頓:一份可運行的流暢方案
有人在群裡問:倒計時放在 ListView 裡特別卡,有沒有靠譜的做法。於是動手實現了一版,供大家參考。 思路 直覺做法是在 Adapter 的 getView 裡給
PopupWindow 使用要點整理:顯示位置、動畫與背景變暗
前幾天要用 PopupWindow,一時想不起怎麼寫,上網查完自己做了個 demo,順手把要點記錄下來。 使用場景 顧名思義,PopupWindow 就是浮動彈窗。Ac