Use Kotlin DSL build Android project

Foreword

Android supports the use of Kotlin DSL to build Gradle script, and not quickly learn a wave?

This article Topic:

1. How to Replace Groovy use Kotlin DSL

2. The problem encountered and solutions

Why should I use Kotlin DSL

Use Kotlin DSL advantages:

  • Because Android is now officially recommended Kotlin language, so use Kotlin Gradle build script language help unify the entire development of the project, no additional learning Groovy syntax
  • Kotlin DSL support jump to the source
  • Kotlin DSL check for errors at compile time
  • Kotlin DSL supports automatic code completion and syntax highlighting

Kotlin DSL disadvantages:

  • Groovy compiler speed slower than

Migrating from Groovy to Kotlin DSL

Gradle Version: 3.5.3

gradle-wrapper Version: 5.6.4

Create a new Android project

We have a new Android project as an example, step by step migration from groovy to Kotlin DSL

The first step: Modify setting.gradle file

To setting.gradlerenamesetting.gradle.kts

All Kotlin DSL document are based on the file name suffix .kts

Then modify the contents of the file inside:

include (":app")

rootProject.buildFileName = "build.gradle.kts"

What this does is very simple, that is the original ":" to "()" This is Kotlin One of the differences DSL and Groovy syntax.

Step two: Modify the Project file of build.gradle

To build.gradlerenamebuild.gradle.kts

Then modify the contents:

buildscript {
    val kotlin_version = "1.3.61" // #1
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.0.0-beta01")  // #2
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

tasks.register("clean", Delete::class) {  // #3
    delete(rootProject.buildDir)
}

The main change here is the three points, I have identified out in the code:

  • ext changed val, val is Kotlin immutable variable keywords
  • classpath single quotation marks to double quotes
  • task also need to change the syntax of Kotlin

The third step: Modify the App's build.gradle file

Similarly, the first build.gradlerenamebuild.gardle.kts

Changes need to do here is more and more, directly on the code changes:

plugins {  // #1
    id("com.android.application")
    kotlin("android")
    kotlin("android.extensions")
}

android {
    compileSdkVersion(29)  // #2
    buildToolsVersion("29.0.3")

    defaultConfig {
        applicationId = "com.bluelzy.kotlindsldemo"
        minSdkVersion(21)
        targetSdkVersion(29)
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        getByName("release") {   // #3
            isMinifyEnabled = false
            proguardFiles (getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
        }
    }
}

dependencies {
    implementation(
        fileTree(  // #4
            mapOf(
                "dir" to "libs", "include" to listOf("*.jar")

            )
        )
    )
    implementation (kotlin(
        "stdlib-jdk7",
        org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION
    ))
    implementation("androidx.core:core-ktx:1.2.0")
    implementation("androidx.appcompat:appcompat:1.1.0")
    implementation("androidx.constraintlayout:constraintlayout:1.1.3")
    testImplementation("junit:junit:4.12")
    androidTestImplementation("androidx.test.ext:junit:1.1.1")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.2.0")

}

Identify areas requiring attention is also out in the notes:

  • apply need to change plugins
  • Original: all the wording changed to () or =, which is the setter syntax kotlin
  • Note the change buildTypes and fileTree

After you complete these steps, we can click sync project, if nothing unexpected happens, then we should be successful, in fact, so far we have been successfully migrated from Groovy to the Kotlin DSL. But I have not found a problem, right now all of our version, version-dependent, TargetSDK etc., are written directly in build.gradle.kts file, can put these variables are unified in one place manage it ? In particular a plurality Module, we just want to change a place, all the dependencies can be synchronized.

In fact, officials have provided us with a solution, and that is to use buildSrc

Step Four: Create a folder buildSrc

BuildSrc create a folder in the root directory, which is the same level and app file folder. Creating result should look like this:

Here Insert Picture Description

You can ignore the first Kotlin folder inside the 3 files. As long as src / main / kotlin and build.gradle.kts files created on it.

Next step is to modify the build.gradle.ktsfiles:

plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

Explain what the role of this buildSrc folder is it?

Official recommended we use this folder to manage dependencies of the project, that is to say, we can define more than the Road King and dependence associated with the class.

Create a file Dependencies.kt

object Apps {
    const val compileSdk = 29
    const val minSdk = 21
    const val targetSdk = 29
    const val versionCode = 1
    const val versionName = "1.0.0"
}

object Versions {
    const val gradle = "3.5.3"
    const val kotlin = "1.3.61"
    const val appcompat = "1.0.2"
    
    /* test */
    const val junit = "4.12"
}

object Libs {
    const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Versions.kotlin}"
    const val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}"
}

object TestLibs {
    const val junit = "junit:junit:${Versions.junit}"
}

For example, we have defined in this document kt three singleton, respectively, for storing the version number associated App dependence associated version number, and the name dependencies

Then we define these constants can spend inside the App's build.gradle.kts

Updated build.gradle.kts:

// 省略代码
android {
    compileSdkVersion(Apps.compileSdk)

    defaultConfig {
        applicationId = "com.bluelzy.kotlindsldemo"
        minSdkVersion(Apps.minSdk)
        targetSdkVersion(Apps.targetSdk)
        versionCode = Apps.versionCode
        versionName = Apps.versionName
    }
	// 省略代码
}

dependencies {

    // android supports
    implementation(Libs.appcompat)

    // test
    testImplementation(TestLibs.junit)
}

The above documents are not complete, you can add yourself to Dependencies.kt file, and the file can be updated build.gradle.kts in accordance with the project dependencies.

If the project has more than Modlue, but also on the relationship is very complex, so we can define several kt multi-file in buildSrc / src / main / kotlin directory for different management dependent. Here not carried out.

to sum up

In fact, steps to use Kotlin DSL instead of Groovy is relatively simple, it is three gradle related rename the file to .kts, and then modify the syntax Kotlin, and finally create a dependency-related kt buildSrc files in the directory.

But you will also encounter some problems in the process, to question my personal experience as an example

1. The project will build successful, can operate normally, but the App's build.gradle.kts file androidlabels and implementationhas been an error, restart AS, clean project, as well as clear the cache can not solve the problem.

If this problem occurs, then you can try to modify gradle version, version gradle I started the project created using:

gradle: 4.0.0-beta01
gradle-wrapper: https://services.gradle.org/distributions/gradle-6.1.1-all.zip

It may be a new version of the Bug, how can not find android
the back I'll be downgraded to gradle:

Gradle Version: 3.5.3

gradle-wrapper Version: 5.6.4

Then it

2. Modify build.gradle.kts file will complain in the process, this time it can open Gradle panel, which found the build setupoption to runinit

Finally, attach a use Kotlin DSL screenshots of build.gradle.kts file is not much clearer than before it?

Here Insert Picture Description

reference

Published 55 original articles · won praise 37 · Views 140,000 +

Guess you like

Origin blog.csdn.net/blue_zy/article/details/104765687