组件化创建全过程
小白都可以看懂的组件化创建全过程,下面是详细步骤:
第一步:在主工程创建 library,比如可以先建一个 custom_base 的Lib,用来给 custom_ui 做专门的数据处理,数据和视图分离,实现解耦
右键主工程 --> New --> Module --> Android Library
custom_base 这个Lib专门写一些基类,或者工具类,供其他UI模块调用
第二步:创建UI模块,比如 custom_ui,也是上面的步骤,只是名字不一样罢了;
在主工程下的 build.gradle 中的 dependencies,引入 custom_ui 模块,否则 这个UI模块启动不了:
implementation project(':custom_ui')
第三步:在 custom_ui 模块下的 build.gradle 中的 dependencies,引入 custom_base 模块:
implementation project(':custom_base')
此时,主工程可以启动 custom_ui 模块,而 custom_ui 模块,又可以调用 custom_base 模块中的基类方法,基本完成目标。
如果,完成了 custom_ui 模块,想单独测试怎么办呢?
Module模块单独测试:
1.首先找到主工程下的 gradle.properties 文件,写在最后一行,定义一个标志:
isSampleDebug=false
注意,false后不要加标点符号。
如果你觉得 isSampleDebug 不好听,随意换一个名字也是可以的。
2.找到 custom_ui 模块的 build.gradle 文件,将第一行(通常是第一行)的 apply plugin: 'com.android.library' 屏蔽:
//apply plugin: 'com.android.library'
//单独工程和lib的声明不同
if (isSampleDebug.toBoolean()) {
apply plugin: 'com.android.application'
} else {
apply plugin: 'com.android.library'
}
实际上就是1步骤定义了一个开关, custom_ui 模块是作为Lib运行,还是单独作为一个Module运行。
3.同上步骤中,build.gradle 文件中 android 括号下,添加
android {
compileSdkVersion 30
buildToolsVersion "30.0.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.0"
//添加开始 作为单独工程,需要设置applicationID
if (isSampleDebug.toBoolean()) {
applicationId "你UI模块的包名"
}
// 添加结束
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
//添加开始
sourceSets {
main {
//单独调试与集成调试时使用不同的 AndroidManifest.xml 文件
if (isSampleDebug.toBoolean()) {
manifest.srcFile 'src/main/debug/AndroidManifest.xml'
} else {
manifest.srcFile 'src/main/AndroidManifest.xml'
java {
//module 模式下要 排除src/test/文件夹下的所有文件
exclude 'src/debug/'
}
}
}
}
// 添加结束
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
添加开始到添加结束的,就是额外需要添加的;
请注意,上面有加载清单文件AndroidManifest,你需要在UI模块main文件下新建debug文件,再将 AndroidManifest 文件Copy过来,此时的清单文件需设置启动的 Activity,这跟平时app下的清单文件是一模一样的,如果资源缺失,你需要把资源copy到UI模块中:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="你UI模块的包名">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
>
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
4 最后一步,在 app 下的 build.gradle 文件中的 dependencies 下添加:
//主工程在组件作为单独工程运行的时候,要过滤到此组件,因为application是不能直接引用application的
if(isSampleDebug.toBoolean()){
runtimeOnly project(':custom_ui')
}else {
implementation project(':custom_ui')
}
此时,你可以选择 custom_ui 模块单独运行了,如果不想单独运行,更改 1步骤中的标志就好了。