背景
在项目中要使用到 ARouter 框架,所以在网上找了很多文章来看,发现对于导入这个步骤讲得很简单,并且多数是Java语法而不是Kotlin,在实际使用中出现了很多问题,因此记录此篇。
简介
ARouter 用于组件化开发架构中的通信功能,并达到解藕。
GitHub网址:https://github.com/alibaba/ARouter
导入步骤
Project 级别
在 build.gradle(Project:XXX)
文件中添加如下代码:
buildscript {
...
ext.arouter_register_version = '1.0.2'
ext.arouter_api_version = '1.5.0'
ext.arouter_compiler_version = '1.2.2'
repositories {
...
mavenCentral()
}
dependencies {
...
classpath "com.alibaba:arouter-register:$arouter_register_version"
}
}
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
module 级别
1. 添加 arouter-api
如果项目中有 lib_base 这种公共模块,并且被其它模块所依赖,就可以直接在公共模块的 build.gradle
文件中添加依赖
api "com.alibaba:arouter-api:$arouter_api_version"
其中 $arouter_api_version
是arouter-api的版本号
要是没有公共模块,就在每个模块中都添加就可以了
2. 添加 arouter-compiler
arouter-compiler 必须添加到每一个模块的 build.gradle
文件中,它是作用在编译期的。
kapt "com.alibaba:arouter-compiler:$arouter_compiler_version"
其中kapt
是 kotlin 语言专用的,和 java 的 annotationProcessor
的作用是一样的。
$arouter_compiler_version
是arouter_compiler的版本号
3. 添加 module 名称
每一个模块都必须添加
kapt {
arguments {
arg("AROUTER_MODULE_NAME", project.getName())
}
}
4. 来一个完整的文件
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt' // 必须有
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.xxx.xxx"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
debuggable false
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
lintOptions { abortOnError false }
}
}
// 必须有
kapt {
arguments {
arg("AROUTER_MODULE_NAME", project.getName())
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// 必须有
kapt "com.alibaba:arouter-compiler:$arouter_compiler_version"
}