AndroidAnnotations是一个能够让你快速进行Android开发的开源框架,它能让你专注于真正重要的地方。使代码更加精简,使项目更容易维护。相比原生的Android App代码量,几乎可以少一半,由于是开源项目,大家可以直接用,具体用法和介绍,大家可以参考下面的GitHub地址:
https://github.com/excilys/androidannotations/wiki
简单说明下Android Studio的配置方法,比较简单,修改对应module的build.gradle文件(注意是对应module的build.gradle文件,不是整个project的build.gradle),添加下面的内容:
dependencies {
.....
/**
* Android Studio配置AndroidAnnotations框架
* https://github.com/excilys/androidannotations/blob/master/examples/gradle/build.gradle
* http://www.cnblogs.com/caobotao/p/5138935.html
*/
compile 'com.github.rey5137:material:1.1.0'
compile 'de.greenrobot:eventbus:2.4.0'
compile 'net.steamcrafted:load-toast:1.0.6'
}
/**
* 下面的部分都是为配置AndroidAnnotations框架添加的
*/
buildscript {
repositories {
mavenCentral()
}
dependencies {
// replace with the current version of the Android plugin
classpath 'com.android.tools.build:gradle:2.1.0-alpha4'
// the latest version of the android-apt plugin
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
}
}
repositories {
mavenCentral()
mavenLocal()
}
apply plugin: 'android-apt'
def AAVersion = '3.3.1'
dependencies {
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
}
apt {
arguments {
androidManifestFile variant.outputs[0].processResources.manifestFile
}
}
使用方法:
从上面的代码可以看出,用@EActivity、@ViewById、@AfterViews、@Click等注解来完成组件的创建、初始化和点击等操作。含义如下:
@EActivity
必须要有一个layout id来表示这个Activity所使用的布局,用来替代setContentView的操作。
@ViewById
和原来的findViewById()方法一样,后面可以跟上每个view id,用来替代组件的初始化操作,值得注意的是:@ViewById后的id是可以不写的,条件是组件变量名称要与xml中定义的id必须一致(方法2)。
@AfterViews
表示在组件初始化完成后在执行,更新组件状态的方法必须加上这个注解,否则会出现空指针。
@Click
表示点击事件,用来完成组件的点击事件的操作。
当然AndroidAnnotations还有很多注解,比如@background表示在子线程运行,@UiThread表示在主线程运行等等。有兴趣的同学可以到Github上学习,里面有详细的介绍,基本上涵盖了所有Android的基本知识。
最需要注意的一点就是:使用AndroidAnnotations千万要记得,编译的时候会生成一个子类,这个类的名称就是在原来的类之后加了一个下划线“_”,比如这个例子产生的子类名称为“MainActivity_”,这就需要你在注册这个Activity的时候,在AndroidManifest.xml中将 MainActivity 改为 MainActivity_ ,使用的时候也是使用MainActivity_来表示此类,跟上面的SecondActivity_类似。
另外上面的MainActivity中跳转的时候还传递了参数,可以用@Extra标签来获取传递的值。
SecondActivity.Java: