編輯:關於 Android 程式設計
ButterKnife 幾乎人人用過,最直接的收益就是省下一堆 findViewById。既然原理不複雜,那我們就自己刻一個,取名 BBKnife。
使用時我們這樣寫:
class ExampleActivity extends Activity {
@BindView(R.id.title) TextView title;
@BindView(R.id.subtitle) TextView subtitle;
@BindView(R.id.footer) TextView footer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
// TODO Use fields...
}
}
編譯之後,它會生成一個與 Activity 同名的輔助類 ExampleActivity$ViewBinder,內容就是那串 findViewById:
public void bind(ExampleActivity activity) {
activity.subtitle = (android.widget.TextView) activity.findViewById(2130968578);
activity.footer = (android.widget.TextView) activity.findViewById(2130968579);
activity.title = (android.widget.TextView) activity.findViewById(2130968577);
}
所以 BBKnife 要做的事就很明確了:在編譯期掃描注解,生成這樣一個輔助類。
新建一個專案,然後新增一個 module,類型選 Java Library。

這個注解作用於屬性上,帶一個整型參數,用法等同 @BindView(R.id.title):
/**
* Created by hanks on 2016/7/31.
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
int value();
}
這裡 Retention 選 CLASS 而不是 RUNTIME,因為我們只需要在編譯期看到它,執行期並不需要反射讀取,這樣也比較省效能。
/**
* 編譯期間處理注解
* Created by hanks on 2016/7/31.
*/
@SupportedAnnotationTypes("xyz.hanks.BindView")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class BindViewProcessor extends AbstractProcessor {
private Messager messager;
public static final String SUFFIX = "$ViewBinder";
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
messager = processingEnv.getMessager();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// key 是類名,value 是該類中帶注解的屬性
Map<String, List<VariableElement>> map = new HashMap<>();
// 遍歷所有被 BindView 標註的元素
for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) {
if (element == null || !(element instanceof VariableElement)) {
continue;
}
VariableElement variableElement = (VariableElement) element;
// 取得屬性所在的類名
String className = element.getEnclosingElement().getSimpleName().toString();
List<VariableElement> variableElementList = map.get(className);
if (variableElementList == null) {
variableElementList = new ArrayList<>();
map.put(className, variableElementList);
}
variableElementList.add(variableElement);
}
generate(map);
return true;
}
private void generate(Map<String, List<VariableElement>> map) {
if (map == null || map.size() == 0) {
return;
}
for (String className : map.keySet()) {
List<VariableElement> variableElementList = map.get(className);
if (variableElementList == null || variableElementList.size() <= 0) {
continue;
}
// 取得完整包名
String packageName = variableElementList.get(0)
.getEnclosingElement().getEnclosingElement().toString();
StringBuilder builder = new StringBuilder()
.append("package ").append(packageName).append(";\n\n")
.append("public class ").append(className).append(SUFFIX).append(" {\n")
.append(" public void bind(Object target) {\n")
.append(" ").append(className).append(" activity = (")
.append(className).append(") target;\n");
for (VariableElement variableElement : variableElementList) {
BindView bindView = variableElement.getAnnotation(BindView.class);
log(bindView.toString());
builder.append(" activity.")
.append(variableElement.getSimpleName().toString())
.append(" = (").append(variableElement.asType()).append(") ")
.append("activity.findViewById(").append(bindView.value()).append(");\n");
}
builder.append(" }\n}\n");
// 輸出檔案
try {
String bindViewClassName = packageName + "." + className + SUFFIX;
JavaFileObject source = processingEnv.getFiler().createSourceFile(bindViewClassName);
Writer writer = source.openWriter();
writer.write(builder.toString());
writer.flush();
writer.close();
} catch (IOException e) {
log(e.getMessage());
}
}
}
private void log(String msg) {
messager.printMessage(Diagnostic.Kind.WARNING, msg);
}
}
幾個實作上的注意事項:
接著在 src/main/resources/META-INF/services 下建立名為 javax.annotation.processing.Processor 的檔案,內容寫上你的處理器完整類名。javac 會自動讀取這個檔案並完成註冊。

呼叫 BBKnife.bind(activity) 時,用反射找到「類名 + $ViewBinder」的輔助類並執行它的 bind 方法:
public class BBKnife {
public static void bind(Object view) {
try {
String cla = view.getClass().getName() + BindViewProcessor.SUFFIX;
Class clazz = Class.forName(cla);
Object instance = clazz.newInstance();
Method bind = clazz.getMethod("bind", Object.class);
bind.invoke(instance, view);
} catch (Exception e) {
e.printStackTrace();
}
}
}
build 之後,build/libs 目錄下就會有對應的 jar 檔。

把 jar 複製到 app 模組的 libs 目錄,並在 build.gradle 中引入 android-apt 外掛:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' // 使用 apt
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "xyz.hanks.bbknifeproject"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.1.1'
}
在 MainActivity 中使用,寫法和 ButterKnife 幾乎一致:
public class MainActivity extends AppCompatActivity {
@BindView(R.id.bb_button) Button mButton;
@BindView(R.id.bb_image) ImageView mImage;
@BindView(R.id.bb_text) TextView mText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BBKnife.bind(this);
mButton.setText("hanks.xyz");
mText.setText("hanks.xyz");
mImage.setImageResource(R.mipmap.ic_launcher);
}
}
編譯後可以觀察到生成的輔助類 MainActivity$ViewBinder.java:
public class MainActivity$ViewBinder {
public void bind(Object target) {
MainActivity activity = (MainActivity) target;
activity.mButton = (android.widget.Button) activity.findViewById(2131427412);
activity.mImage = (android.widget.ImageView) activity.findViewById(2131427414);
activity.mText = (android.widget.TextView) activity.findViewById(2131427413);
}
}

這篇真正練習到的不是「怎麼省 findViewById」,而是三個更有價值的能力:
把同一套骨架換成 @OnClick、@BindString 甚至自訂的日誌切面,都不難。真正要留意的是執行期的反射開銷——這也是 ButterKnife 選擇編譯期生成程式碼、而不是執行期反射的原因。
自訂 View 實作九宮格滑動解鎖:從座標比對到手勢路徑
九宮格解鎖曾經是各家 Android 手機的標準配備。它的實作比看起來精緻:需要自訂 View、處理觸控事件、維護九個圓點的座標表、記錄使用者劃過的序列,最後還要把路徑畫
Android 中使用 Pull 解析 XML 數據的完整示例
Pull 解析 XML 的方式與 SAX 大致相同,兩者都是基於事件驅動的。使用 Pull 解析 XML 通常需要以下幾個步驟: 1)通過 XMLPullParserFa
Android 入門:跑通第一個 OpenCV 程式
剛接觸 Android 開發時,由於先前對 OpenCV 較為熟悉,於是便想先在 Android 上把 OpenCV 跑起來。本文記錄了從環境配置到實現攝像頭即時影像處理
Glide 快取大小查詢與清理的完整工具類實作
一、Glide 內建的清快取方法 Glide 本身提供了兩個清理方法:clearDiskCache() 清除磁碟快取,clearMemory() 清除記憶體快取。使用時有