在android中有多种框架,如GreenDroid这样的UI框架,能够统一UI布局,也有Volley这样的网络框架,能够方便的加载网络资源并缓存。
但除此之外呢?
Annotation的作用又是什么呢?
我们都知道,在Activity中我们要加载layout中的控件,需要使用到id属性,可以通过如findViewById()的方式,加载到控件。但这样重复代码太多了!!
我们可以想象下,一个布局如果有3,40个控件,我们是不是要写3,40个findViewById()呢?这样也太麻烦了,而且也无从省略!!
这时就可以使用Annotation框架。
AndroidAnnotations是一个能够让你快速进行Android开发的开源框架,它能让你专注于真正重要的地方。
使代码更加精简,使项目更加容易维护
他的特性:
1、使用依赖注入(Dependency Injection)#本博接来下几篇的文章将要介绍的开源组件都使用DI, 不熟悉
的可以了解一下Inversion of Control(IoC)
2、简化的线程模型(Simplified threading model)
3、事件绑定(Event binding)
4、REST Client
5、No Magic [不知道为什么这样称呼,直译过来就是:无魔法,它的意思是:AndroidAnnotations在编译
的时候会产生一个子类(接下来你会明白),你查看这个子类,可以看到它是如何工作的]
AndroidAnnotations的配置见:
http://blog.sina.com.cn/s/blog_8025389f0101egrv.html
AndroidAnnotations的使用:
首先从实例的HelloWorld开始:
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
@ViewById
EditText myEditText;
@ViewById(R.id.myTextView)
TextView textView;
@StringRes(R.string.hello)
String helloFormat;
@ColorRes
int androidColor;
@BooleanRes
boolean someBoolean;
@SystemService
NotificationManager notificationManager;
@SystemService
WindowManager windowManager;
}
如上面代码,使用了如EActivity ,ViewById,StringRes,ColorRes等注解。
首先@EActivity后必须要有一个layout id 来表示这
个Activity所使用的布局,远来的onCreate方法就不用了
新的OnCreate方法如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// windowManager should not be null
windowManager.getDefaultDisplay();
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
}
即不需要setContentView(R.layout.activity_main);了!!
上面的windowManager上面通过@SystemService已经定义过了,不需要再通过
windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
的方式获取,而是直接可以使用。
同理上面的:
@ViewById(R.id.myTextView)
TextView textView;
即@ViewById 就和原来
的findViewById()方法一样,值得注意的是:@ViewById后的id是可以不写的,条件是控件变量名称要与xml中定义的id
必须一致,也就是说 当我在xml文件中定义的TextView的id必须是:android:id="@+id/textView" . 这样我们在@ViewById
后就不用再写括号了,直接写
如上面的:
@ViewById
EditText myEditText;
在对应的layout中有如下控件:
<EditText
android:id="@+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
点击事件:
如图所示,即可以设置点击事件:
而该button1标示的则不需要,如下:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
运行结果如图所示:
最后注意要修改清单文件,Activity类的名字会变化!!
使用AndroidAnnotations千万要记得,编译的时候会生成一个子类,这个子类的名称就是在
原来的类之后加了一个下划线“_”,比如这个例子产生的子类名称为“MyActivity_”,这就需要你在注册这个Activity的时候,在
AndroidManifest.xml中将 MyActivity 改为 MyActivity_ ,使用的时候也是使用MyActivity_来表示此类
如:
Intent intent = ActivityWithExtra_.intent(this).myDate(new Date()).myMessage("hello !").get();
<activity
android:name="com.luan.annotationTest.MainActivity_"
android:label="@string/app_name" >