开源项目androidannotation使用
介绍
1 目标
我们希望使编写和维护代码更便利.
我们相信意图清晰、简明的代码,是达到这一目标的最佳途径.
Robert C. Martin 这样说道:
阅读代码所花费的时间,相比编写代码要超过10倍.
因为使代码容易阅读,将使它更容易编写.
当我们潜心于开发android应用时,我们常常惊讶于:
- 为毛我们经常需要写一些重复的代码?
- 为毛我们的app越来越难以维护?
- Context和Activity这种上帝对象
- 复杂以至于捉弄你的线程机制
- 难以捉摸的API
- 匿名监听器类的加载
- 成吨成吨不必要的转型
- more and more….
So, 为毛我们不改善它呢!!!!!!
2 怎样做
- 使用JAVA注解, 开发者能展现他们的意图,并使用AndroidAnnotations在编译时自动产生模版代码.
- That sounds cool!
特点
- 依赖注入
- 注入views, extras, system services, resources, …
- 简化的线程模型
- 通过方法的注解,决定他们在UI线程或是背景线程里面跑起来!
- 事件绑定
- 通过方法的注解,处理各种view的各种事件
- 不再需要各种匿名的监听器了, 因为他们丑的一匹
- 整合Rest Client
- 创建一个客户端接口, AndroidAnnotations自动搞定实现
- 拒绝魔法
- 当AndroidAnnotations在编译期生成子类时, 你可以check代码, 看清楚它们是怎样工作的.
- 浓缩的都是精华
- 这么好的东西,居然只有不到150KB
- 还特么没有运行时开销
- (兄弟,你赚大了)
下一步
示例代码
嘿, 你的代码真的易读,易写,还易于维护吗?
就像下面这段:
@EActivity(R.layout.translate) // Sets content view to R.layout.translate
public class TranslateActivity extends Activity {
@ViewById // Injects R.id.textInput
EditText textInput;
@ViewById(R.id.myTextView) // Injects R.id.myTextView
TextView result;
@AnimationRes // Injects android.R.anim.fade_in
Animation fadeIn;
@Click // When R.id.doTranslate button is clicked
void doTranslate() {
translateInBackground(textInput.getText().toString());
}
@Background // Executed in a background thread
void translateInBackground(String textToTranslate) {
String translatedText = callGoogleTranslate(textToTranslate);
showResult(translatedText);
}
@UiThread // Executed in the ui thread
void showResult(String translatedText) {
result.setText(translatedText);
result.startAnimation(fadeIn);
}
// [...]
}
版权声明
- 项目logo基于android logo,由Google创建并分享,并按照创作共用许可证3.0协议中的条款使用
- Android是Goolge inc拥有商标,使用这个商标必须获得Google的许可
- AndroidAnnotations由Pierre-Yves Ricau 创建,而eBusinessInformations提供了最初的赞助.