天天看点

Android 模块化

1、

创建项目、创建几个模块,比如下面几个模块

Android 模块化

common_core创建是androidlib类型的,它是核心模块比如你封装的网络请求,还有通用的工具类,common_bussiness也是androidlib类型的,这里是你的业务模块公共的部分,而index_module是module类型的,是具体的业务模块这里只是举个例子,像常见的有用户模块(注册登录)我的模块(用户信息、设置等)

2、

在gradle.properties中添加isBuildModule,当isBuildModule=true则各个模块可以独立运行,当isBuildModule=false则可以将项目进行合并,注意在common_core中添加依赖时必须使用api 而不是implementation 因为implementation依赖的库只在当前module中有效,要想其他模块依赖了common_core就可以随意调用内部依赖的库的话必须使用api进行依赖。

Android 模块化

在index_module的build.gradle中头部修改为

if (isBuildModule.toBoolean()) {
    apply plugin: 'com.android.application'
} else {
    apply plugin: 'com.android.library'
}      

这样当isBuildModule为true时该模块就可以单独运行,而false时则为lib

3、

当isBuildModule为false时,关于模块之间activity跳转与交互则是借助ARouter进行跳转的。

需要在module的build.gradle中的defaultConfig{}中添加

javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
                includeCompileClasspath true
            }
        }      

4、

关于在模块化中使用Butterknife,需要注意2点

(1)在module中需要使用R2代替R,如下

​​

​@BindView(R2.id.tv) TextView tv;​

​ (2)在module中需要使用if else代替switch case

@OnClick({R2.id.tv,R2.id.tv2})
    public void onViewClicked(View view) {
        if (R.id.tv==view.getId()){
            Toast.makeText(getApplicationContext(),"index",Toast.LENGTH_SHORT).show();
        }else if (R.id.tv2==view.getId()){
            Toast.makeText(getApplicationContext(),"hello world",Toast.LENGTH_SHORT).show();
        }
    }
      

5、

每个module在设置isBuildModule=true 时,可以独立运行调试,因此,manifest也应该是2套的,因此需要在module的build.gradle 中sourceSets{}中添加:

sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
            if (isBuildModule.toBoolean()) {
                manifest.srcFile 'src/main/debug/AndroidManifest.xml'
            } else {
                manifest.srcFile 'src/main/AndroidManifest.xml'
            }
        }
    }      

6、

apply from: "../module_build.gradle"