編輯:關於 Android 程式設計
新增 module 時務必選擇 Java Library,否則後續會找不到 AbstractProcessor。接著在 app 與 processor 的 build.gradle 加入:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
此模組用來保存專案用到的 annotation:
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.CLASS;
@Retention(CLASS)
@Target(FIELD)
public @interface BindView {
int value();
}
public class MainActivity extends AppCompatActivity {
@BindView(R.id.text_view) TextView textView;
@BindView(R.id.view) TextView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
在 processor 模組下建立 ButterKnifeProcessor,繼承 AbstractProcessor:
@SupportedAnnotationTypes("com.chiclaim.processor.annotation.BindView")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class ButterKnifeProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
StringBuilder builder = new StringBuilder()
.append("package com.chiclaim.processor.generated;\n\n")
.append("public class GeneratedClass {\n\n")
.append("\tpublic String getMessage() {\n")
.append("\t\treturn \"");
for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) {
String objectType = element.getSimpleName().toString();
builder.append(objectType).append(" says hello!\n");
}
builder.append("\";\n")
.append("\t}\n")
.append("}\n");
try {
JavaFileObject source = processingEnv.getFiler()
.createSourceFile("com.chiclaim.processor.generated.GeneratedClass");
Writer writer = source.openWriter();
writer.write(builder.toString());
writer.flush();
writer.close();
} catch (IOException e) {
// 首次執行後檔案已存在所引發的 IO 錯誤屬正常現象
}
return true;
}
}
其中 @SupportedAnnotationTypes(...) 的參數即為我們要處理的注解。
在 processor 模組的 resources 目錄下建立 META-INF/services,新增名為 javax.annotation.processing.Processor 的檔案,內容為 ButterKnifeProcessor 的 qualified name:
com.chiclaim.butterknife.processor.ButterKnifeProcessor
當然,也可以不必手動建立這層層目錄——只要引入 Google AutoService,它就會自動完成上述動作:
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@AutoService(Processor.class) // 自動產生 META-INF/services/javax.annotation.processing.Processor
public class ButterKnifeProcessor extends AbstractProcessor { ... }
在全域 build.gradle 加入 apt 支援 com.neenbedankt.gradle.plugins:android-apt:1.8:
buildscript {
repositories { jcenter() }
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
ext {
sourceCompatibilityVersion = JavaVersion.VERSION_1_7
targetCompatibilityVersion = JavaVersion.VERSION_1_7
}
allprojects { repositories { jcenter() } }
task clean(type: Delete) { delete rootProject.buildDir }
在 app 模組的 build.gradle 套用外掛:
apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile project(':annotation')
compile project(':processor')
compile project(':butterknife')
}
// 把 processor 模組產生的 jar 複製到 app 的 libs
task processorTask(type: Exec) {
commandLine 'cp', '../processor/build/libs/processor.jar', 'libs/'
}
processorTask.dependsOn(':processor:build')
preBuild.dependsOn(processorTask)
如圖所示:

會在 app 模組的 build 目錄下產生對應程式碼:

public class GeneratedClass {
public String getMessage() {
return "button says hello!\nimageView says hello!\ntextView says hello!\nview says hello!\n";
}
}
至此,在 Android Studio 中使用 APT 的流程便介紹完畢。
Android 線程優先級怎麼設?一次搞懂 Process.setThreadPriority
多線程寫得多了,你一定遇過這種尷尬:明明邏輯沒錯,畫面卻總是卡一下。問題往往不在演算法,而在 CPU 時間的分配。 Android 上的並發場景比桌面端更敏感。設備的算
Android 開發學習之路:Camera 初體驗
顧名思義,Camera 就是拍照與錄像的功能。就拿微信來說,當我們想拍照傳給好友時,其實不必直接調用 Camera API——因為系統一般都自帶相機程式,直接調用系統相機
Android 自定義圖形單點移動與縮放效果
單點拖曳在單指操作時,可透過 MotionEvent 取得目前座標,並更新檢視的 LayoutParams 邊距,讓圖形跟著手指移動。這種方式適合需要直接操控位置的簡單互
Android 九宮格解鎖自定義實作
效果與思路 九宮格解鎖是常見的 Android 互動模式。當手指點到某個格子,該格會進入選取狀態;滑動時,從目前格子連線到手指位置;抬起時,比對走過的格子順序是否與預設密