LoginSignup
12
9

More than 5 years have passed since last update.

【Android】dependenciesをIDE補完で記述する

Last updated at Posted at 2019-02-14

はじめに

Androidアプリのdependenciesを下記のように記述していないでしょうか?

build.gradle
...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

このように記述すると、バージョン変更時に一つずつ編集しなければならなかったり、そもそも可読性が低いように感じます。
そこで、buildSrcでこれらを保持する方法が良さそうだったのでメモしておきます。

参考:
Kotlin + buildSrc for Better Gradle Dependency Management

やり方

1. buildSrcフォルダを作成

モジュールと同じようにプロジェクトルートにbuildSrcという名前のフォルダを作成します。

2. build.gradle.ktsを作成

作成したbuildSrcフォルダにbuild.gradle.ktsという名前のkotlin-scriptファイルを作成します。
この段階ではまだ何も記述しなくていいです。

3. Sync Gradle !

sync gradleしましょう。buildSrc内に以下のようなファイルが生成されれば成功です。

4. dslを記述

build.gradle.ktsに以下を記述してsync gradleしましょう。

build.gradle.kts
plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

5. Dependencyを保持するオブジェクトクラスを作成

buildSrc内にsrc/main/java/Dependencies.ktを作成します。

一旦今のDependencyを全て保持させておきたいので、下記のようにします。

Dependencies.kt
object Dependencies {
    object Version {
        val kotlin = "1.2.71"
        val support = "28.0.0"
        val constraint = "1.1.3"
        val runner = "1.0.2"
        val espresso = "3.0.2"
    }

    val kotlinLib = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Version.kotlin}"
    val appCompat = "com.android.support:appcompat-v7:${Version.support}"
    val constraintLayout = "com.android.support.constraint:constraint-layout:${Version.constraint}"
    val junit = "junit:junit:4.12"
    val testRunner = "com.android.support.test:runner:${Version.runner}"
    val espressoCore = "com.android.support.test.espresso:espresso-core:${Version.espresso}"
}

6. 実際に使う

これで使えるようになりました! 実際にbuild.gradleに適用しましょう!

build.gradle
...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation Dependencies.kotlinLib
    implementation Dependencies.appCompat
    implementation Dependencies.constraintLayout
    testImplementation Dependencies.junit
    androidTestImplementation Dependencies.testRunner
    androidTestImplementation Dependencies.espressoCore
}

以前と比べて何を読み込んでいるか分かりやすくなり、IDE補完が効くので編集もしやすくなったかと思います。

サンプル

今回のプロジェクトをGitHubに上げたので、よければ参考にしてください。
https://github.com/TaigaNatto/BuildSorceSample

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9