浅析ButterKnife的实现 (一) —— 搭建开发框架

ButterKnife的大名相信做Android开发的都应该知道,如果你还不知道那只能说明你平时都没关注过开源项目,优秀的开源项目对于开发来说帮助是巨大的,而学习优秀的开源项目对个人的提升帮助也是巨大的。ButterKnife通过注解的方式帮助我们处理诸如 findViewById()和setonclicktListener()等的重复性繁琐的工作,极大地减轻了程序员的工作量。ButterKnife的实现原理是通过定义编译时注解(RetentionPolicy.CLASS),并在注解处理器中对这些注解进行处理,最终生成 Java代码,我们只要简单地调用个bind() 方法就可以完成所有工作,非常的方便。而且它用的是编译时注解,和运行时注解相比对性能的影响是很小的。

简单介绍了ButterKnife,下面来开始来系统地学习ButterKnife是怎么实现的。写这文章是出于学习ButterKnife的实现原理为目的,我会从一个项目的搭建开始来逐渐实现ButterKnife的主要功能,整个设计思想还是遵循ButterKnife原本的设计思想。我是以自己的理解来说明ButterKnife为什么要这样设计,其中如果有偏差也欢迎帮忙指正。这开源项目也有很多关于注解和注解处理器的运用方法很值得借鉴学习,对于这方面的提升是个非常不错的学习材料。

搭建开发所需要的框架

在进行开发前,有必要先把整个开发框架搭起来,因为涉及到编译时对注解进行处理,所以和平时开发稍微有点不同,这边需要创建两个Java库,而不单单只是Android项目。如果对编译时注解开发不清楚的先看这里:自定义注解之编译时注解(RetentionPolicy.CLASS)(一)这里面已经写的很详细了,我这里就只做简单的说明,不清楚可以看那篇文章。

首先我们需要创建3个库,一个Android库和两个Java库,大体如下:


每个模块用来做什么上面已经标注的很清楚,我们来看下各个模块的 build.gradle 文件。

butterknife-annotations

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. apply plugin: 'java'  
  2.   
  3. // 因为依赖 com.android.support:support-annotations 需要添加这几段话  
  4. def logger = new com.android.build.gradle.internal.LoggerWrapper(project.logger)  
  5. def sdkHandler = new com.android.build.gradle.internal.SdkHandler(project, logger)  
  6. for (File file : sdkHandler.sdkLoader.repositories) {  
  7.     repositories.maven {  
  8.         url = file.toURI()  
  9.     }  
  10. }  
  11.   
  12. dependencies {  
  13.     compile fileTree(include: ['*.jar'], dir: 'libs')  
  14.     sourceCompatibility = 1.7  
  15.     targetCompatibility = 1.7  
  16.   
  17.     compile 'com.android.support:support-annotations:23.4.0'  
  18. }  

在这个注解库里依赖了一个android库:com.android.support:support-annotations,因为这个注解库是Java工程,要想依赖到这个库需要添加上面标识的那几段话。至于这几段话的具体作用,我还没有查到资料- -,我是从ButterKnife开源代码里copy出来的,如果有知道也麻烦告诉我下。那么为什么要依赖这个库呢?这是因为我们在定义注解时需要用到这里面的一些系统定义好的注解,如:@StringRes、@IdRes 这类限定注解,使我们定义的注解可以更好地工作。

butterknife-compiler

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. apply plugin: 'java'  
  2.   
  3. // 因为 butterknife-annotations 依赖 com.android.support:support-annotations 需要添加这几段话  
  4. def logger = new com.android.build.gradle.internal.LoggerWrapper(project.logger)  
  5. def sdkHandler = new com.android.build.gradle.internal.SdkHandler(project, logger)  
  6. for (File file : sdkHandler.sdkLoader.repositories) {  
  7.     repositories.maven {  
  8.         url = file.toURI()  
  9.     }  
  10. }  
  11.   
  12. dependencies {  
  13.     compile fileTree(include: ['*.jar'], dir: 'libs')  
  14.     sourceCompatibility = 1.7  
  15.     targetCompatibility = 1.7  
  16.     compile project(':butterknife-annotations')  
  17.     compile 'com.google.auto.service:auto-service:1.0-rc2'  
  18.     compile 'com.squareup:javapoet:1.7.0'  
  19.     compile 'com.google.auto:auto-common:0.6'  
  20. }  

和 butterknife-annotations 一样,这里也需要添加那几段话,因为它也是个Java库并包含了注解库。除此之外,这里还依赖了另外3个库:auto-service、javapoet和 auto-common。其中前两个在之前的文章都有提到过,而最后一个库主要提供元素有效性的检测,这些用来帮助注解开发的库都很有用,极大地简化了开发工作,后面都会提到它们的用法。

butterknifelib

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. apply plugin: 'com.android.library'  
  2.   
  3. android {  
  4.     compileSdkVersion 23  
  5.     buildToolsVersion "24.0.0 rc2"  
  6.   
  7.     defaultConfig {  
  8.         minSdkVersion 14  
  9.         targetSdkVersion 23  
  10.         versionCode 1  
  11.         versionName "1.0"  
  12.     }  
  13.     buildTypes {  
  14.         release {  
  15.             minifyEnabled false  
  16.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  17.         }  
  18.     }  
  19. }  
  20.   
  21. dependencies {  
  22.     compile fileTree(include: ['*.jar'], dir: 'libs')  
  23.     testCompile 'junit:junit:4.12'  
  24.     compile 'com.android.support:appcompat-v7:23.4.0'  
  25.     compile project(':butterknife-annotations')  
  26. }  

这就是一个标准的Android库了,它需要依赖 butterknife-annotations 注解库,其它就没什么需要注意的了。

app主项目

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. apply plugin: 'com.android.application'  
  2. apply plugin: 'com.neenbedankt.android-apt'  
  3.   
  4. android {  
  5.     compileSdkVersion 23  
  6.     buildToolsVersion "24.0.0 rc2"  
  7.   
  8.     defaultConfig {  
  9.         applicationId "com.dl7.butterknife"  
  10.         minSdkVersion 14  
  11.         targetSdkVersion 23  
  12.         versionCode 1  
  13.         versionName "1.0"  
  14.     }  
  15.     buildTypes {  
  16.         release {  
  17.             minifyEnabled false  
  18.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  19.         }  
  20.     }  
  21. }  
  22.   
  23. dependencies {  
  24.     compile fileTree(include: ['*.jar'], dir: 'libs')  
  25.     testCompile 'junit:junit:4.12'  
  26.     compile 'com.android.support:appcompat-v7:23.4.0'  
  27.     compile 'com.android.support:support-annotations:23.4.0'  
  28.     apt project(':butterknife-compiler')  
  29.     compile project(':butterknifelib')  
  30. }  

这里依赖了 butterknifelib 库,并加入了 android-apt,关于 android-apt 具体设置请参考之前的文章,除了这边要设置外,主工程的 build.gradle 也要设置如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. buildscript {  
  2.     repositories {  
  3.         jcenter()  
  4.         mavenCentral()  
  5.     }  
  6.     dependencies {  
  7.         classpath 'com.android.tools.build:gradle:2.1.2'  
  8.         classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'  
  9.         // NOTE: Do not place your application dependencies here; they belong  
  10.         // in the individual module build.gradle files  
  11.     }  
  12. }  

这样整个开发框架就搭好了,下面就开始进行功能实现。

定义 butterknifelib 的接口

我们需要在 butterknifelib 中提供接口供外部调用,来作为整个绑定操作的主入口方法,并在里面处理所有注入操作。

首先定义一个绑定接口,如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 绑定接口 
  3.  */  
  4. public interface ViewBinder<T> {  
  5.   
  6.     /** 
  7.      * 处理绑定操作 
  8.      * @param finder 这个用来统一处理Activity、View、Dialog等查找 View 和 Context 的方法 
  9.      * @param target 进行绑定的目标对象 
  10.      * @param source 所依附的对象,可能是 target 本身,如果它是 Activity、View、Dialog 的话 
  11.      */  
  12.     void bind(Finder finder, T target, Object source);  
  13. }  

为什么要定义个接口呢?因为后面我们通过处理注解生成的Java类都要实现这个接口,这样我们通过反射获取到对应类的时候就可以直接显示转换成这个接口,并调用里面的 bind() 方法来执行具体操作。至于这3个参数的意思如标注所示,Finder我们下面会讲,对于 source参数我举个例子:比如我们要进行绑定操作的 target 对象是个 Fragment 的话,它的 source 就是通过 LayoutInflater.inflate() 返回的View,它所绑定的视图都是和这个 View关联的,通过这个View 我们才能找到我们的其它视图资源。

我们来看下  Finder 的实现:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 资源查找的处理类 
  3.  */  
  4. @SuppressWarnings("UnusedDeclaration"// Used by generated code.  
  5. public enum Finder {  
  6.     VIEW {  
  7.         @Override  
  8.         protected View findView(Object source, int id) {  
  9.             return ((View) source).findViewById(id);  
  10.         }  
  11.   
  12.         @Override  
  13.         public Context getContext(Object source) {  
  14.             return ((View) source).getContext();  
  15.         }  
  16.   
  17.         @Override  
  18.         protected String getResourceEntryName(Object source, int id) {  
  19.             final View view = (View) source;  
  20.             // In edit mode, getResourceEntryName() is unsupported due to use of BridgeResources  
  21.             if (view.isInEditMode()) {  
  22.                 return "<unavailable while editing>";  
  23.             }  
  24.             return super.getResourceEntryName(source, id);  
  25.         }  
  26.     },  
  27.     ACTIVITY {  
  28.         @Override  
  29.         protected View findView(Object source, int id) {  
  30.             return ((Activity) source).findViewById(id);  
  31.         }  
  32.   
  33.         @Override  
  34.         public Context getContext(Object source) {  
  35.             return (Activity) source;  
  36.         }  
  37.     },  
  38.     DIALOG {  
  39.         @Override  
  40.         protected View findView(Object source, int id) {  
  41.             return ((Dialog) source).findViewById(id);  
  42.         }  
  43.   
  44.         @Override  
  45.         public Context getContext(Object source) {  
  46.             return ((Dialog) source).getContext();  
  47.         }  
  48.     };  
  49.   
  50.     // 略...  
  51.   
  52.     /** 
  53.      * findViewById 
  54.      * @param source 
  55.      * @param id 
  56.      * @return 
  57.      */  
  58.     protected abstract View findView(Object source, int id);  
  59.   
  60.     /** 
  61.      * 获取Context 
  62.      * @param source 
  63.      * @return 
  64.      */  
  65.     public abstract Context getContext(Object source);  
  66. }  

这里我先省略了一些方法,只讲现在必要的东西。这个枚举类型中定义了3个不同的枚举对象,分别对应 Activity、View、Dialog等,并都实现了下面两个抽象方法。你仔细看它们的实现就可以看出来,这里把 findViewById(id)和getContext() 做了统一封装,这样我们后面调用的时候不用再去关心它对应的到底是哪种类型,直接调用方法就行了。

再来看下提供外部调用的接口类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 提供资源绑定接口的类 
  3.  */  
  4. public class ButterKnife {  
  5.   
  6.     static final Map<Class<?>, ViewBinder<Object>> BINDERS = new LinkedHashMap<>();  
  7.   
  8.     private ButterKnife() {  
  9.         throw new AssertionError("No instances.");  
  10.     }  
  11.   
  12.     /** 
  13.      * 绑定 Activity 
  14.      * @param target 目标为 Activity 
  15.      */  
  16.     public static void bind(@NonNull Activity target) {  
  17.         _bind(target, target, Finder.ACTIVITY);  
  18.     }  
  19.     /** 
  20.      * 绑定目标对象 
  21.      * @param target 目标为 Object 
  22.      * @param source 依附 Activity 
  23.      */  
  24.     public static void bind(@NonNull Object target, @NonNull Activity source) {  
  25.         _bind(target, source, Finder.ACTIVITY);  
  26.     }  
  27.   
  28.     /** 
  29.      * 绑定 View 
  30.      * @param target 目标为 View 
  31.      */  
  32.     public static void bind(@NonNull View target) {  
  33.         _bind(target, target, Finder.VIEW);  
  34.     }  
  35.     /** 
  36.      * 绑定目标对象 
  37.      * @param target 目标为 Object 
  38.      * @param source 依附 View 
  39.      */  
  40.     public static void bind(@NonNull Object target, @NonNull View source) {  
  41.         _bind(target, source, Finder.VIEW);  
  42.     }  
  43.   
  44.     /** 
  45.      * 绑定 Dialog 
  46.      * @param target 目标为 Dialog 
  47.      */  
  48.     public static void bind(@NonNull Dialog target) {  
  49.         _bind(target, target, Finder.DIALOG);  
  50.     }  
  51.     /** 
  52.      * 绑定目标对象 
  53.      * @param target 目标为 Object 
  54.      * @param source 依附 Dialog 
  55.      */  
  56.     public static void bind(@NonNull Object target, @NonNull Dialog source) {  
  57.         _bind(target, source, Finder.DIALOG);  
  58.     }  
  59.   
  60.     /** 
  61.      * 资源绑定 
  62.      * @param target 目标 
  63.      * @param source 来源:activity、dialog 或 view 
  64.      * @param finder 辅助查找的工具,配合source使用 
  65.      */  
  66.     private static void _bind(@NonNull Object target, @NonNull Object source, @NonNull Finder finder) {  
  67.         Class<?> targetClass = target.getClass();  
  68.         try {  
  69.             ViewBinder<Object> viewBinder = _findViewBinderForClass(targetClass);  
  70.             if (viewBinder != null) {  
  71.                 // 执行bind方法进行资源绑定  
  72.                 viewBinder.bind(finder, target, source);  
  73.             }  
  74.         } catch (Exception e) {  
  75.             throw new RuntimeException("Unable to bind views for " + targetClass.getName(), e);  
  76.         }  
  77.     }  
  78.   
  79.     /** 
  80.      * 通过目标Class找到对应的ViewBinder 
  81.      * @param cls Class 
  82.      * @return ViewBinder 
  83.      * @throws IllegalAccessException 
  84.      * @throws InstantiationException 
  85.      */  
  86.     private static ViewBinder<Object> _findViewBinderForClass(Class<?> cls)  
  87.             throws IllegalAccessException, InstantiationException {  
  88.         ViewBinder<Object> viewBinder = BINDERS.get(cls);  
  89.         if (viewBinder != null) {  
  90.             return viewBinder;  
  91.         }  
  92.         String clsName = cls.getName();  
  93.         if (clsName.startsWith("android.") || clsName.startsWith("java.")) {  
  94.             return null;  
  95.         }  
  96.         try {  
  97.             // 利用反射来生成对应 ViewBinder  
  98.             Class<?> viewBindingClass = Class.forName(clsName + "$$ViewBinder");  
  99.             viewBinder = (ViewBinder<Object>) viewBindingClass.newInstance();  
  100.         } catch (ClassNotFoundException e) {  
  101.             // 查找父类是否存在  
  102.             viewBinder = _findViewBinderForClass(cls.getSuperclass());  
  103.         }  
  104.         BINDERS.put(cls, viewBinder);  
  105.         return viewBinder;  
  106.     }  
  107. }  

这里重载了多个 bind() 方法对应不同的调用对象,在该方法里会通过反射去获取在编译时期生成的类(生成的类名统一规定为:target对象的className + "$$ViewBinder" 后缀),如果能创建对应的实例则调用实例的 bind() 方法。

这样 butterknifelib 的工作就大体处理好了,当然了,在实际开发中一般不太可能能一次性就先把这些东西都定义好,而是配合注解处理来做调整完善。

定义注解处理器

最后再定义一个注解处理器,整个开发框架就差不多了,我们后面的工作基本都是完善注解的处理。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 注解处理器 
  3.  */  
  4. @AutoService(Processor.class)  
  5. public class ButterKnifeProcessor extends AbstractProcessor {  
  6.   
  7.     private Types typeUtils;  
  8.     private Elements elementUtils;  
  9.     private Filer filer;  
  10.     private Messager messager;  
  11.   
  12.     @Override  
  13.     public synchronized void init(ProcessingEnvironment processingEnv) {  
  14.         super.init(processingEnv);  
  15.         typeUtils = processingEnv.getTypeUtils();  
  16.         elementUtils = processingEnv.getElementUtils();  
  17.         filer = processingEnv.getFiler();  
  18.         messager = processingEnv.getMessager();  
  19.     }  
  20.   
  21.     @Override  
  22.     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {  
  23.         return false;  
  24.     }  
  25.   
  26.     @Override  
  27.     public Set<String> getSupportedAnnotationTypes() {  
  28.         Set<String> annotations = new LinkedHashSet<>();  
  29.         return annotations;  
  30.     }  
  31.   
  32.     @Override  
  33.     public SourceVersion getSupportedSourceVersion() {  
  34.         return SourceVersion.latestSupported();  
  35.     }  
  36. }  

这样前期工作都处理完了,后面就开始真正的注解开发了。

项目代码:ButterKnifeStudy


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值