編輯:關於 Android 程式設計
註解是 Android 開發中降低樣板程式碼的關鍵手段。要真正理解 ButterKnife、EventBus、Dagger 這些框架為什麼效能差異那麼大,得先分清「執行期註解」與「編譯期註解」這兩條完全不同的技術路線。
定義:註解是可以附加到 Java 原始碼中的語法中繼資料。類別、方法、變數、參數、套件都能被標註,用來把中繼資料與程式元素關聯起來。最常見的例子莫過於 @Override 與 @Deprecated。
元註解是「用來描述註解」的基本註解,所有自訂註解都離不開它。共四個:
SOURCE:只保留在原始碼中,不寫入 class 檔,也不載入虛擬機。
CLASS:保留在原始碼與 class 檔中,但不載入虛擬機。
RUNTIME:保留在原始碼、class 檔中,最終載入虛擬機。
兩條路線的實質差別就在這裡:
AbstractProcessor 的類別並改寫 process(),在其中把註解資訊轉譯成你要的程式碼。
ElementType.FIELD:變數
ElementType.METHOD:方法
ElementType.PARAMETER:參數
ElementType.CONSTRUCTOR:建構子
ElementType.LOCAL_VARIABLE:區域變數
ElementType.PACKAGE:套件
是否可被繼承,預設 false。
是否收錄進 Javadoc 文件。
@Override:標示該方法改寫自父類。編譯時會檢查,若父類中並無此方法則報錯。@Deprecated:標示該方法已不建議使用,代表它有風險或已有更好的替代。@SuppressWarnings:編譯時忽略指定的警告類型,例如版本檢查。@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String name() default "";
int id() default 0;
}
關鍵字是 @interface。上方標註的元註解表明:這個註解只能修飾方法,且會保留到執行期。內部宣告的則是它擁有的屬性,都帶了預設值。
使用時在方法上標註並給值:
@TestAnnotation(name = "android", id = 1)
private void testAnno() { }
再透過反射把它讀出來:
private void outputAnnoDetail(Class clazz) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
TestAnnotation testAnnotation = method.getAnnotation(TestAnnotation.class);
if (testAnnotation != null) {
Log.d("annotation", "name------>" + testAnnotation.name()
+ "------>id------>" + testAnnotation.id());
}
}
}
輸出:
name------>android------>id------>1
這是一個執行期註解。歸根結底,註解的作用就是標記一個可被識別的作用域,讓別人在執行期以反射讀取,或在編譯期由編譯器/註解處理器解析。
ButterKnife 主要負責綁定 View 與其監聽事件。看它的 @BindView:
@Retention(CLASS)
@Target(FIELD)
public @interface BindView {
/** 該欄位要綁定的 View ID */
@IdRes int value();
}
注意 @Retention(CLASS)——它保留到 class 檔但不載入虛擬機。凡標為 CLASS 的註解,通常都會配套一個 AbstractProcessor 實作,在編譯階段完成處理。看幾個關鍵方法:
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> types = new LinkedHashSet<>();
for (Class<? extends Annotation> annotation : getSupportedAnnotations()) {
types.add(annotation.getCanonicalName());
}
return types;
}
private Set<Class<? extends Annotation>> getSupportedAnnotations() {
Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>();
annotations.add(BindArray.class);
annotations.add(BindBitmap.class);
annotations.add(BindBool.class);
annotations.add(BindColor.class);
annotations.add(BindDimen.class);
annotations.add(BindDrawable.class);
annotations.add(BindFloat.class);
annotations.add(BindInt.class);
annotations.add(BindString.class);
annotations.add(BindView.class);
annotations.add(BindViews.class);
annotations.addAll(LISTENERS);
return annotations;
}
這段在宣告:處理器要接管哪些註解。
@Override
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
Map<TypeElement, BindingSet> bindingMap = findAndParseTargets(env);
for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
TypeElement typeElement = entry.getKey();
BindingSet binding = entry.getValue();
JavaFile javaFile = binding.brewJava(sdk);
try {
javaFile.writeTo(filer);
} catch (IOException e) {
error(typeElement, "Unable to write binding for type %s: %s",
typeElement, e.getMessage());
}
}
return true;
}
這裡就是編譯期的具體處理流程:先找出並解析所有標註目標,再依解析結果產生 Java 原始碼。等到 App 真正在裝置上執行時,findViewById 與 setOnClickListener 的呼叫已經被寫死進那些自動產生的類別裡,完全不必再做查找與解析,也就沒有執行期反射的負擔。這正是編譯期註解在效能上的根本優勢。
EventBus 走的是另一條路:執行時才去找出所有被標註的方法,再逐一解析。好處是寫法直觀、侵入性低;代價是每一次事件分發都伴隨反射查找的開銷。因此實務上的結論是——執行期註解通常只適合標記「作用範圍」,把真正的效能關鍵路徑留給編譯期方案或明確的介面實作。
判斷標準很簡單:這段處理是每次執行都要做一次,還是只需要在編譯時算一次?只要結果在編譯期就能確定(視圖綁定、事件綁定、依賴注入的圖形結構),就應該用編譯期註解把它前移。只有在資訊必須等到執行期才知道時(例如事件訂閱關係、執行期才決定的策略),執行期註解才是合理選擇。
Android 自訂進度條:偽裝成「載重格」的兩種實作方案對比
有些設計稿上的進度條不是一條長條,而是像貨車載重格那樣一格一格亮起來。這種效果有兩種做法:一是用容器動態塞子 View,二是自己寫一個自訂 View 用 Canvas 畫
ListView 使用與性能優化:從基礎寫法到分批加載
一、ListView 的標準使用步驟 1. 定制實體類,把要填進列表的字段定義好,配齊 set / get 方法; 2. 自定義 item 布局,按數據需要排版; 3.
揭開 RecyclerView 的神秘面紗(二):三種實戰處理點擊事件
前言 上一篇《揭開 RecyclerView 的神秘面紗(一):RecyclerView 的基本使用》中介紹了 RecyclerView 的基本用法,以及不同版面配置管理
微信小視頻存在哪裡?儲存路徑與哪些情況不會留檔
發過朋友圈小視頻的人大概都有過這樣的困擾:動態刪了,影片也跟著找不到。想找回來,就得知道它實際被存到了哪裡。 微信小視頻的儲存路徑 預設位置是:sdcard0/Tence