Create a Kotlin library in Android Studio

前端 未结 2 764
再見小時候
再見小時候 2021-02-05 01:58

I am very new to both the Android and JVM platforms. Using Android Studio, I would like to create an Android app and put most of my business logic in a library. I would also li

相关标签:
2条回答
  • 2021-02-05 02:26

    You need a module with no Android dependencies and resources - this is what a Java library module does, so you start by creating one of those. From there, you just need to enable Kotlin inside this module.

    The build.gradle file you get when you create your module is something like this:

    apply plugin: 'java-library'
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
    }
    

    You need to add the Kotlin plugin and standard library. If you don't have the mavenCentral repository added for all modules in your project yet, you need to add that as well:

    apply plugin: 'java-library'
    apply plugin: 'kotlin'
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    }
    
    repositories {
        mavenCentral()
    }
    

    This is assuming that you have a kotlin_version declared in your project level build.gradle file, which is the usual way for Android projects, and I believe that's how Android Studio configures a project if you tick the checkbox to use Kotlin.


    With those changes to your library's build.gradle, you can remove the automatically generated MyClass.java file from your library's source folder (/src/main/java/your/package/name), and start adding Kotlin files instead. If you'd like, you can also rename the /src/main/java folder to /src/main/kotlin. Or you can use both folders, this is entirely up to you.

    0 讨论(0)
  • 2021-02-05 02:48

    Create Android studio project After that create as many as module which are basically Android library You can select the language of module (java/kotlin)

    Extra Upload your module to github and use jitpcak tool to make your module a library like this Implementation 'com. My. Module:1.0'

    And use your module any future project

    0 讨论(0)
提交回复
热议问题