天天看点

5. Android 框架ButterKnife源代码分析

一. ButterKnife介绍

在Android编程过程中,我们会写大量的布局和点击事件,像初始view、设置view监听这样简单而重复的操作,这些代码繁琐而又不雅观,比如:

<code>TextView tvSetName = findViewById(R.id.xxx);</code>

<code>tvSetName.setOnClickListener(</code><code>new</code> <code>View.OnClickListener() {</code>

<code>    </code><code>@Override</code>

<code>    </code><code>public</code> <code>void</code> <code>onClick(View v) {</code>

<code>        </code><code>//xxxx</code>

<code>    </code><code>}</code>

<code>});</code>

<code>TextView tvSetAge = findViewById(R.id.xxx);</code>

<code>tvSetAge.setOnClickListener(</code><code>new</code> <code>View.OnClickListener() {</code>

<code>TextView tvSetArea = findViewById(R.id.xxx);</code>

<code>tvSetArea.setOnClickListener(</code><code>new</code> <code>View.OnClickListener() {</code>

Activity中这种代码多了之后,很不雅观。

二. 使用简介

ButterKnife使用方法比较简单,主要包括以下步骤:

引用ButterKnife包

在onCreate里面bind(setContentView之后)

绑定各种事件

onDestroy里面解绑释放资源

<a href="http://blog.csdn.net/itjianghuxiaoxiong/article/details/50177549" target="_blank">ButterKnife使用方法</a>

三. ButterKnife源代码下载

<a href="https://github.com/JakeWharton/butterknife" target="_blank">ButterKnife github源代码地址</a>

直接git clone或者下载zip即可。

四. 编译

Android studio打开ButterKnife源代码

AndroidStudio-&gt;File-&gt;open-&gt;ButterKnife源代码路径-&gt;确认

Build-&gt;Rebuild Project

五. 生成的aar和jar包

生成的包主要有两个

butterknife-annotations-8.5.2-SNAPSHOT.jar

路径:butterknife-annotations-&gt;build-&gt;libs

butterknife-release.aar

路径: butterknife-&gt;build-&gt;outputs-&gt;aar

六. 其他应用引用自定义ButterKnife包 

删除原来ButterKnife包引用,因为要使用自己编译的包

拷贝文件

拷贝上面两个文件到自己项目app模块的libs 目录

添加aar的关联

打开app模块的build.gradle文件,添加:

<code>compile fileTree(include: ['*.jar'], dir: 'libs')</code>

<code>compile(name: 'butterknife-release', ext: 'aar')</code>

七. 源代码分析

1. ButterKnife.bind(Activity target)过程

文件名:ButterKnife.java

<code>static</code> <code>final</code> <code>Map&lt;Class&lt;?&gt;, Constructor&lt;? </code><code>extends</code> <code>Unbinder&gt;&gt; BINDINGS = </code><code>new</code> <code>LinkedHashMap&lt;&gt;();</code>

<code>public</code> <code>static</code> <code>Unbinder bind(</code><code>@NonNull</code> <code>Activity target) {</code>

<code>    </code><code>Log.d(</code><code>"Sandy"</code><code>, </code><code>"ButterKnife bind.. target: "</code> <code>+ target);</code>

<code>    </code><code>View sourceView = target.getWindow().getDecorView();</code>

<code>    </code><code>return</code> <code>createBinding(target, sourceView);</code>

<code>}</code>

<code>private</code> <code>static</code> <code>Unbinder createBinding(</code><code>@NonNull</code> <code>Object target, </code><code>@NonNull</code> <code>View source) {</code>

<code>    </code><code>Class&lt;?&gt; targetClass = target.getClass();</code>

<code>    </code><code>if</code> <code>(debug) Log.d(TAG, </code><code>"Looking up binding for "</code> <code>+ targetClass.getName());</code>

<code>    </code><code>Constructor&lt;? </code><code>extends</code> <code>Unbinder&gt; constructor = findBindingConstructorForClass(targetClass);</code>

<code>    </code><code>if</code> <code>(constructor == </code><code>null</code><code>) {</code>

<code>      </code><code>return</code> <code>Unbinder.EMPTY;</code>

<code>    </code><code>//noinspection TryWithIdenticalCatches Resolves to API 19+ only type.</code>

<code>    </code><code>try</code> <code>{</code>

<code>      </code><code>return</code> <code>constructor.newInstance(target, source);</code>

<code>    </code><code>} </code><code>catch</code> <code>(IllegalAccessException e) {</code>

<code>      </code><code>throw</code> <code>new</code> <code>RuntimeException(</code><code>"Unable to invoke "</code> <code>+ constructor, e);</code>

<code>    </code><code>} </code><code>catch</code> <code>(InstantiationException e) {</code>

<code>    </code><code>} </code><code>catch</code> <code>(InvocationTargetException e) {</code>

<code>      </code><code>Throwable cause = e.getCause();</code>

<code>      </code><code>if</code> <code>(cause </code><code>instanceof</code> <code>RuntimeException) {</code>

<code>        </code><code>throw</code> <code>(RuntimeException) cause;</code>

<code>      </code><code>}</code>

<code>      </code><code>if</code> <code>(cause </code><code>instanceof</code> <code>Error) {</code>

<code>        </code><code>throw</code> <code>(Error) cause;</code>

<code>      </code><code>throw</code> <code>new</code> <code>RuntimeException(</code><code>"Unable to create binding instance."</code><code>, cause);</code>

<code>private</code> <code>static</code> <code>Constructor&lt;? </code><code>extends</code> <code>Unbinder&gt; findBindingConstructorForClass(Class&lt;?&gt; cls) {</code>

<code>    </code><code>Constructor&lt;? </code><code>extends</code> <code>Unbinder&gt; bindingCtor = BINDINGS.get(cls);</code>

<code>    </code><code>if</code> <code>(bindingCtor != </code><code>null</code><code>) {</code>

<code>      </code><code>if</code> <code>(debug) Log.d(TAG, </code><code>"HIT: Cached in binding map."</code><code>);</code>

<code>      </code><code>return</code> <code>bindingCtor;</code>

<code>    </code><code>String clsName = cls.getName();</code>

<code>    </code><code>if</code> <code>(clsName.startsWith(</code><code>"android."</code><code>) || clsName.startsWith(</code><code>"java."</code><code>)) {</code>

<code>      </code><code>if</code> <code>(debug) Log.d(TAG, </code><code>"MISS: Reached framework class. Abandoning search."</code><code>);</code>

<code>      </code><code>return</code> <code>null</code><code>;</code>

<code>        </code><code>Log.d(</code><code>"Sandy"</code><code>, </code><code>"findBindingConsForClass: "</code> <code>+ clsName + </code><code>" vindBinding name: "</code> <code>+</code>

<code>                </code><code>clsName + </code><code>"_ViewBinding"</code><code>);</code>

<code>      </code><code>Class&lt;?&gt; bindingClass = cls.getClassLoader().loadClass(clsName + </code><code>"_ViewBinding"</code><code>);</code>

<code>      </code><code>//noinspection unchecked</code>

<code>      </code><code>bindingCtor = (Constructor&lt;? </code><code>extends</code> <code>Unbinder&gt;) bindingClass.getConstructor(cls, View.</code><code>class</code><code>);</code>

<code>      </code><code>if</code> <code>(debug) Log.d(TAG, </code><code>"HIT: Loaded binding class and constructor."</code><code>);</code>

<code>    </code><code>} </code><code>catch</code> <code>(ClassNotFoundException e) {</code>

<code>      </code><code>if</code> <code>(debug) Log.d(TAG, </code><code>"Not found. Trying superclass "</code> <code>+ cls.getSuperclass().getName());</code>

<code>      </code><code>bindingCtor = findBindingConstructorForClass(cls.getSuperclass());</code>

<code>    </code><code>} </code><code>catch</code> <code>(NoSuchMethodException e) {</code>

<code>      </code><code>throw</code> <code>new</code> <code>RuntimeException(</code><code>"Unable to find binding constructor for "</code> <code>+ clsName, e);</code>

<code>    </code><code>BINDINGS.put(cls, bindingCtor);</code>

<code>    </code><code>return</code> <code>bindingCtor;</code>

上面这段代码有几个注意点:

a. sourceView代表是DecorView,也就是我们窗口的顶级View。

b. findBindingConstructorForClass有个BINDINGS缓存,key是class,value是缓存的Unbinder对象,这样做可以加快bind速度。

因为每个类的ButterKnife注解在运行期间是不会变的,比如MainActivity有3个ButterKnife注解,那么它就是3个。除非有新的apk安装。

所以适合用缓存来实现。

c. findBindingConstructorForClass使用了递归的方法

这个方法使用了递归,不断调用父类,也就是

<code>catch</code> <code>(ClassNotFoundException e) {</code>

那为什么要这么处理呢?

因为有些Activity没有ButterKnife的注解,但是它的父类可能有,比如BaseActivity。所以需要往上递归。那什么时候递归结束呢?

<code>if</code> <code>(bindingCtor != </code><code>null</code><code>) {</code>

如果缓存里面找到了结果,那么结束,同时返回结果;

或者类名以"android."或者"java."开头,也结束,返回null;

以Activity为例,Activity的类名是android.app.Activity,所以你的MainActivity如果递归到Activity还没有找到ButterKnife注解,那就说明你的MainActivity是没有包含ButterKnife注解的。

d. 如果子Activity和父Activity都有ButterKnife注解怎么办?

答案是返回子Activity以及其对应的 Constructor&lt;? extends Unbinder&gt; bindingCtor对象

那它的父Activity如果也有ButterKnife注解怎么办?怎么解析父Activity的ButterKnife注解呢? 这个问题我们待会再讲。

记为问题1。

e. Constructor&lt;? extends Unbinder&gt; 是个什么东西?

调用ButterKnife.bind(Activity target)方法后会返回一个Unbinder对象,可以在onDestroy中调用unbind()方法,那个Unbinder是什么东西呢?这个问题待会再讲。

记为问题2.

f. clsName + "_ViewBinding"是什么类?

Class&lt;?&gt; bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding");

这个问题记为问题3.

2. ButterKnifeProcessor.java

这个类是ButterKnife里面很重要的一个类了,它继承自AbstractProcessor。

看来不懂的问题越来越多,那么有必要来学习下Java注解的知识。

八. Java注解

在分析ButterKnife代码前,需要了解Java的注解,需要了解Annotation Processor,因为ButterKnifer用到这个知识。

这里面很重要的一个知识点就是你可以编写一定的规则,让它在应用程序编译时执行你的规则,然后生成Java代码;并且生成的Java还可以参与编译。

<a href="https://race604.com/annotation-processing/" target="_blank">Java注解</a>

九. 自己定义的注解框架

1. Eclipse实现

主要是参考这篇帖子完成的,大家可以参考这篇帖子:

<a href="http://blog.csdn.net/lmj623565791/article/details/43452969" target="_blank">Eclipse中使用Java注解Processor</a>

主要说下不同的地方:

a. source folder的创建,直接File-&gt;New-&gt;source folder一直创建不成功,后面用另外一种方法创建成功了。

项目-&gt;右击-&gt;Properties-&gt;Java Build Path-&gt;Source-&gt;Add Folder-&gt;Create New Folder-&gt;输入resources/META-INF/services-&gt;finish-&gt;ok-&gt;ok

<a href="https://s1.51cto.com/wyfs02/M00/95/55/wKiom1kUG_CSP3OvAACTzaqjj0w123.png-wh_500x0-wm_3-wmp_4-s_4260205487.png" target="_blank"></a>

2. Android studio实现

<a href="http://blog.csdn.net/a1018875550/article/details/52166916" target="_blank">AndroidStudio下面使用Java注解Processor</a>

十. 调试自己的自定义框架

有个时候需要调试自己写的框架是否正常运行,下面介绍下调试:

1. 在项目gradle.properties里面添加

<code>org.gradle.daemon=true</code>

<code>org.gradle.jvmargs=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8011</code>

2.Edit Configureations

<a href="https://s3.51cto.com/wyfs02/M02/95/5D/wKioL1kUUgXzetkqAADJBDdHWVg272.png-wh_500x0-wm_3-wmp_4-s_189248235.png" target="_blank"></a>

3. 增加远程调试

<a href="https://s5.51cto.com/wyfs02/M00/95/5D/wKiom1kUUlWiJR1iAADIV1Xx2G0912.png-wh_500x0-wm_3-wmp_4-s_1570904271.png" target="_blank"></a>

4. 启动远程调试

<a href="https://s4.51cto.com/wyfs02/M01/95/5D/wKioL1kUUqSykGMqAAAtwfDm2S0203.png-wh_500x0-wm_3-wmp_4-s_1078494978.png" target="_blank"></a>

下面的控制台会出现下面的提示:

Connected to the target VM, address: 'localhost:8011', transport: 'socket'

5. 打断点

在Processor里面打上断点,比如init, process

6. 连上手机,项目根目录命令行下执行

gradle clean connectedCheck

十一. ButterKnife使用Java注解

理解了Java注解Processor之后,ButterKnife就比较好理解了。

首先它的ButterKnifeProcessor.java继承自AbstractProcessor,重写了init和process之类的方法。

也就是说它在编译的时候会被执行,生成辅助代码。

它的辅助代码生成到哪里了呢?

在我们自己的应用程序里面搜索_ViewBinding,就可以找到已经生成好的辅助类,如下:

<code>public</code> <code>class</code> <code>xxxx_ViewBinding&lt;T </code><code>extends</code> <code>LoginCloudActivity&gt; </code><code>extends</code> <code>BaseActivity_ViewBinding&lt;T&gt; {</code>

<code>  </code><code>private</code> <code>View view2131689593;</code>

<code>  </code><code>@UiThread</code>

<code>  </code><code>public</code> <code>xxxx_ViewBinding(</code><code>final</code> <code>T target, View source) {</code>

<code>    </code><code>super</code><code>(target, source);</code>

<code>    </code><code>View view;</code>

<code>    </code><code>target.mEtUser = Utils.findRequiredViewAsType(source, R.id.et_user, </code><code>"field 'mEtUser'"</code><code>, EditText.</code><code>class</code><code>);</code>

<code>    </code><code>target.mEtPwd = Utils.findRequiredViewAsType(source, R.id.et_pwd, </code><code>"field 'mEtPwd'"</code><code>, EditText.</code><code>class</code><code>);</code>

<code>    </code><code>view = Utils.findRequiredView(source, R.id.btn_login, </code><code>"method 'btn_login' and method 'btn_login_long'"</code><code>);</code>

<code>    </code><code>view2131689593 = view;</code>

<code>    </code><code>view.setOnClickListener(</code><code>new</code> <code>DebouncingOnClickListener() {</code>

<code>      </code><code>@Override</code>

<code>      </code><code>public</code> <code>void</code> <code>doClick(View p0) {</code>

<code>        </code><code>target.btn_login();</code>

<code>    </code><code>});</code>

<code>    </code><code>view.setOnLongClickListener(</code><code>new</code> <code>View.OnLongClickListener() {</code>

<code>      </code><code>public</code> <code>boolean</code> <code>onLongClick(View p0) {</code>

<code>        </code><code>return</code> <code>target.btn_login_long();</code>

<code>  </code><code>}</code>

<code>  </code><code>@Override</code>

<code>  </code><code>public</code> <code>void</code> <code>unbind() {</code>

<code>    </code><code>T target = </code><code>this</code><code>.target;</code>

<code>    </code><code>super</code><code>.unbind();</code>

<code>    </code><code>target.mEtUser = </code><code>null</code><code>;</code>

<code>    </code><code>target.mEtPwd = </code><code>null</code><code>;</code>

<code>    </code><code>view2131689593.setOnClickListener(</code><code>null</code><code>);</code>

<code>    </code><code>view2131689593.setOnLongClickListener(</code><code>null</code><code>);</code>

<code>    </code><code>view2131689593 = </code><code>null</code><code>;</code>

这个类在编译的时候会被自动生成,那么在运行的时候,它会被调用。

这个类的构造函数会去初始化那些控件,设置监听。

回到第七步 ButterKnife.bind()的过程

在createBinding的时候,它会初始化这个xxx_ViewBinding类,如下:

<code>      </code><code>...</code>

<code>      </code> 

那么就会走到xxx_ViewBinding的构造函数,那么就会初始化控件,同时也会设置监听。如下:

<code>target.mEtUser = Utils.findRequiredViewAsType(source, R.id.et_user, </code><code>"field 'mEtUser'"</code><code>, EditText.</code><code>class</code><code>);</code>

它的调用方式直接是target.mEtpwd,所以也就是说Activity的mEtpwd控件不能是private的,否则会引用不到。

参考网址:

<a href="https://github.com/JakeWharton/butterknife" target="_blank">butterknife github源代码下载</a>

<a href="http://blog.csdn.net/chenkai19920410/article/details/51020151" target="_blank">ButterKnife源代码解析</a>

<a href="https://race604.com/annotation-processing/" target="_blank">Java注解处理器分析</a>

<a href="http://blog.csdn.net/lmj623565791/article/details/43452969" target="_blank">Eclipse中使用Java注解处理器</a>

<a href="http://blog.csdn.net/a1018875550/article/details/52166916" target="_blank">Android studio使用java注解处理器</a>

<a href="http://www.jianshu.com/p/95f12f72f69a" target="_blank">JavaPoet介绍</a>

<a href="http://blog.csdn.net/pizza_lawson/article/details/52126325" target="_blank">调试Java注解处理器出错</a>

     本文转自rongwei84n 51CTO博客,原文链接:http://blog.51cto.com/483181/1924089,如需转载请自行联系原作者

继续阅读