如何在Android Studio Gradle中从项目向模块添加库依赖

4
我创建了一个名为Sample App的Android项目,并在其中创建了一个库模块。由于示例应用程序依赖于其他库,因此我将所需的jar文件添加到Sample App的libs文件夹中。同样的jar文件也需要在模块内使用。
如何让模块依赖于示例应用程序的libs文件夹呢?我尝试了下面的方法,但每次都会出现重复复制文件的异常。
repositories {
    flatDir { dirs '../libs' }
}

compile fileTree(dir: '../libs', include: '*.jar')
5个回答

1
将以下内容添加到您应用程序的build.gradle中:

Add this to your app's build.gradle:

dependencies {
    ....
    compile project(':module-name')
}

嗨Jay,我已经在我的app build.gradle中添加了compile project(':module-name')。但是我的问题是,我想在我的模块中使用应用程序的库。也就是说,我的应用程序和模块都想要使用相同的依赖项。 - sathish
@sathish 请查看此解决方案,可能会对你有所帮助 https://dev59.com/oGEi5IYBdhLWcg3wjc3E - Jay Rathod

1
如果您希望将库(*.jar / *.aar)对整个项目可见,则需要使其位置对所有项目可见。
项目的 gradle 文件:
allprojects {
    repositories {
        jcenter()
        flatDir {
            // This is where the *.jar or *.aar should be located
            dirs "$rootProject.projectDir/libs"
        }
    }
}

例子

有以下目录结构:

SampleApp/
|--- app/
|--- libs/
     \--- myLibrary.aar
|--- myModule/
|--- build.gradle (<-- Project's gradle file)
\--- settings.gradle

以下是依赖关系图表:

compile - Classpath for compiling the main sources.
|--- project :myModule
    \--- :myLibrary:
\--- :myLibrary:

然后

SampleApp的build.gradle文件:

dependencies {
    compile project (":myModule")
    compile (name: 'myLibrary', ext: 'aar')
    // ...
}

myModule的build.gradle:

dependencies {
    compile (name: 'myLibrary', ext: 'aar')
    // ...
}

0

为了在Android Studio中添加模块依赖,请按照以下说明:

您应该将库模块放置在应用程序项目内。为了指定模块依赖关系,只需执行以下操作:

Right click on Application->Open Module Settings
Click on the '+' icon
Select the root directory for your library module you'd like to add.
Follow the prompts

然后,这个模块将会出现在你的项目中。接着,你需要将它作为库依赖添加到应用程序中。再次,在你的模块设置中:
Select your Application module
Select the Dependencies tab on the right
Click the '+' icon on the bottom
Select Module Dependency
Select your desired library module

嗨,Jaimin,感谢您的回复。但是我找不到模块名称前面的复选框。我想将公共库添加到应用程序和其模块中。 - sathish
然后,去谷歌搜索一下,希望GoogleBaba能够给你很多帮助! - Jaimin Modi

0
在应用级别的 build.gradle 文件中。
 dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:support-v13:22.2.1'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'

    compile files('lib/universal-image-loader-1.9.3.jar')

    }

你假设universal-image-loader-1.9.3.jar已经添加到lib文件夹中。 - Dilip
这是(libs),不是(lib)! - IgorGanapolsky

0
如果您正在使用 Kotlin DSL,请将以下内容添加到 build.gradle.kts 文件中:
dependencies {
    ....
    implementation(project(":your-library-module"))
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接