Android开发之Android studio 3.0配置androidannotations及踩坑

3.0配置教程

不要造轮子,参考其它教程:https://blog.csdn.net/lazyox_2008/article/details/79761115
不过它的代码部分有点问题,我来优化下

优化后教程

1.先修改工程目录下的build.gradle文件,删除对应的Apt配置

buildscript {  
    repositories {  
        jcenter()  
        google()  
        mavenCentral()  
    }  
    dependencies {  
        //这里的gradle版本需要3.0.1及以上  
        classpath 'com.android.tools.build:gradle:3.0.1'  

         //classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' //3.0之前的配置,这里需要删除  
 }  
}  
//多项目的集中配置,多数构建工具,对于子项目的配置,都是基于继承的方式。Gradle除了提供继承方式设置子项目,还提供这种配置  
allprojects {  
    repositories {  
        jcenter()  
        google()  
        mavenCentral()  
    }  
}  

2.修改Moudle下的gradle配置,看下面红字的注释,即可配置成功,androidannotations的版本用最新版本吧,我用3.3.2的就不能编译成功,用4.4.0便可以了

apply plugin: 'com.android.application'  

def AAVersion = '4.4.0'  

android {  
    compileSdkVersion rootProject.ext.compileSdkVersion  

    defaultConfig {  
        applicationId "xx.xx.xxx"  
        minSdkVersion rootProject.ext.minSdkVersion  
        targetSdkVersion rootProject.ext.targetSdkVersion  
        versionCode 7  
        versionName "1.4.7"  

        // 添加下面这一段到defaultConfig下面
        javaCompileOptions {  
            annotationProcessorOptions {  
            //这里的包名和applicationId一致  
             arguments = ['resourcePackageName': "xx.xx.xxx"]  
            }  
        }  
    }  
}  

dependencies {  
    implementation fileTree(include: ['*.jar'], dir: 'libs')  
    //3.0之后的用法
    annotationProcessor "org.androidannotations:androidannotations:$AAVersion"  
    implementation "org.androidannotations:androidannotations-api:$AAVersion"  

    //3.0之前的用法,这里注释掉,修改为上面的用法
    //apt "org.androidannotations:androidannotations:$AAVersion"  
    //compile "org.androidannotations:androidannotations-api:$AAVersion"  

}  
//3.0之前的用法,这里修改为defaultConfig里面的用法
//apt {  
//    arguments {  
//        androidManifestFile variant.outputs[0].processResources.manifestFile  
//        resourcePackageName 'com.nexgo.mposdemo'  
//    }  
//}  

踩坑

1.在onCreate里直接调用textAppName.setText()会报空指针
原因:因为在onCreate()被调用的时候,@ViewById还没有被set,也就是都为null,所以如果你要对组件进行一定的初始化,那么你要用@AfterViews注解
解决办法:

    @AfterViews
    public void init(){
        textAppName.setText("hahahha");//把代码放到这里即可
    }

参考文章

1.Android studio 3.0配置androidannotations
2.Android框架Annotations浅析

你可能感兴趣的:(Android开发之Android studio 3.0配置androidannotations及踩坑)