Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發實戰:手把手打造屬於你的 ButterKnife 框架(二)

編輯:關於 Android 程式設計

一、建立專案與 processor 模組

新增 module 時務必選擇 Java Library,否則後續會找不到 AbstractProcessor。接著在 app 與 processor 的 build.gradle 加入:

 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

二、建立 annotation 模組

此模組用來保存專案用到的 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();
}

三、在 MainActivity 加上注解

 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);
    }
}

四、撰寫 ButterKnifeProcessor

在 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)

在 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 { ... }

六、加入 android-apt 支援

在全域 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 的流程便介紹完畢。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved