AndroidAnnotationsについて
AnroidAnnotationsという便利なライブラリがあったので使い方等をメモ。
AndroidAnnotationsとはアノテーションを使用してコードのスリム化を行い見通しの良いコードを記載するためのライブラリです。
公式サイトはこちらです。
概要
AndroidAnnotationsではapt (Annotation Processing Tool)という仕組みを使用しています。
例えば@EActivity
というアノテーションが付加されたActivityがあった場合、このActivityのクラス名の末尾にアンダースコアが付加されたサブクラスが生成されます。
例としては以下のような形になります。
package com.some.company; @EActivity public class MyActivity extends Activity { // ... }
この場合、同じパッケージ名で別のソースフォルダ内にサブクラスが生成されます。
package com.some.company; public final class MyActivity_ extends MyActivity { // ... }
なので、AndroidManifest.xmlにはActivity名は以下のように記載します。
<activity android:name=".MyListActivity_" />
startActivityで呼び出す際は以下のように記載します。
startActivity(this, MyActivity_.class);
導入
AndroidStudioに導入する例を紹介したいと思います。
使用しているAndroidStudioのバージョンは1.1.0になります。
AndroidAnnotatiosを導入するために、build.gradleに記述していく必要があります。
参考はこちらです。
ProjectRoot/build.gradle
まずはプロジェクトディレクトリの直下にあるbuild.gradleに対して以下のように編集を行います。
以下はサンプルとなります。
buildscript { repositories { mavenCentral() } dependencies { // replace with the current version of the Android plugin classpath 'com.android.tools.build:gradle:1.1.0' // replace with the current version of the android-apt plugin classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' } } allprojects { repositories { mavenCentral() } }
app/build.gradle
続いてappディレクトリ内にあるbuild.gradleのサンプルです。
apply plugin: 'com.android.application' apply plugin: 'android-apt' def AAVersion = 'XXX' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.myproject.package" minSdkVersion 14 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } // This is only needed if you project structure doesn't fit the one found here // http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Project-Structure sourceSets { main { // manifest.srcFile 'src/main/AndroidManifest.xml' // java.srcDirs = ['src/main/java', 'build/generated/source/apt/${variant.dirName}'] // resources.srcDirs = ['src/main/resources'] // res.srcDirs = ['src/main/res'] // assets.srcDirs = ['src/main/assets'] } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' apt "org.androidannotations:androidannotations:$AAVersion" compile "org.androidannotations:androidannotations-api:$AAVersion" } apt { arguments { androidManifestFile variant.outputs[0].processResources.manifestFile resourcePackageName 'com.myproject.package' // If you're using Android NBS flavors you should use the following line instead of hard-coded packageName // resourcePackageName android.defaultConfig.packageName // You can set optional annotation processing options here, like these commented options: // logLevel 'INFO' // logFile '/var/log/aa.log' } }
利用可能なアノテーション
結構な数のアノテーションが利用可能です。
さすがに全てを紹介するのは難しいので、上記のページから使用用途に合わせて調べてみてください。