如何在 Android Studio 中添加一个库项目?

How do I add a library project (such as Sherlock ABS) to Android Studio?

(Not to the old ADT Eclipse-based bundle, but to the new Android Studio.)

转载于:https://stackoverflow.com/questions/16588064/how-do-i-add-a-library-project-to-android-studio

csdnceshi77
狐狸.fox Here is a video which I found to be really useful: youtube.com/watch?v=1MyBO9z7ojk
接近 6 年之前 回复
csdnceshi75
衫裤跑路 If you're using Gradle, see this StackOverflow answer.
大约 6 年之前 回复
csdnceshi59
ℙℕℤℝ The YouTube video How to Add Libraries to Android Studio explains the process.
接近 7 年之前 回复
csdnceshi55
~Onlooker yeah figuring this out was way more confusing than it should have been... not like it was any better in eclipse.
7 年多之前 回复

30个回答

Update for Android Studio 1.0

Since Android Studio 1.0 was released (and a lot of versions between v1.0 and one of the firsts from the time of my previous answer) some things has changed.

My description is focused on adding external library project by hand via Gradle files (for better understanding the process). If you want to add a library via Android Studio creator just check the answer below with visual guide (there are some differences between Android Studio 1.0 and those from screenshots, but the process is very similar).

Before you start adding a library to your project by hand, consider adding the external dependency. It won’t mess in your project structure. Almost every well-known Android library is available in a Maven repository and its installation takes only one line of code in the app/build.gradle file:

dependencies {
     compile 'com.jakewharton:butterknife:6.0.0'
}

Adding the library

Here is the full process of adding external Android library to our project:

  1. Create a new project via Android Studio creator. I named it HelloWorld.
  2. Here is the original project structure created by Android Studio:
HelloWorld/
      app/
           - build.gradle  // local Gradle configuration (for app only)
           ...
      - build.gradle // Global Gradle configuration (for whole project)
      - settings.gradle
      - gradle.properties
      ...
  1. In the root directory (HelloWorld/), create new folder: /libs in which we’ll place our external libraries (this step is not required - only for keeping a cleaner project structure).
  2. Paste your library in the newly created /libs folder. In this example I used PagerSlidingTabStrip library (just download ZIP from GitHub, rename library directory to „PagerSlidingTabStrip" and copy it). Here is the new structure of our project:
HelloWorld/
      app/
           - build.gradle  // Local Gradle configuration (for app only)
           ...
      libs/
           PagerSlidingTabStrip/
                - build.gradle // Local Gradle configuration (for library only)
      - build.gradle // Global Gradle configuration (for whole project)
      - settings.gradle
      - gradle.properties
      ...
  1. Edit settings.gradle by adding your library to include. If you use a custom path like I did, you have also to define the project directory for our library. A whole settings.gradle should look like below:

    include ':app', ':PagerSlidingTabStrip'
    project(':PagerSlidingTabStrip').projectDir = new File('libs/PagerSlidingTabStrip')
    

5.1 If you face "Default Configuration" error, then try this instead of step 5,

    include ':app'
    include ':libs:PagerSlidingTabStrip'
  1. In app/build.gradle add our library project as an dependency:

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:21.0.3'
        compile project(":PagerSlidingTabStrip")
    }
    

6.1. If you followed step 5.1, then follow this instead of 6,

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:21.0.3'

        compile project(":libs:PagerSlidingTabStrip")
    }
  1. If your library project doesn’t have build.gradle file you have to create it manually. Here is example of that file:

        apply plugin: 'com.android.library'
    
        dependencies {
            compile 'com.android.support:support-v4:21.0.3'
        }
    
        android {
            compileSdkVersion 21
            buildToolsVersion "21.1.2"
    
            defaultConfig {
                minSdkVersion 14
                targetSdkVersion 21
            }
    
            sourceSets {
                main {
                    manifest.srcFile 'AndroidManifest.xml'
                    java.srcDirs = ['src']
                    res.srcDirs = ['res']
                }
            }
        }
    
  2. Additionally you can create a global configuration for your project which will contain SDK versions and build tools version for every module to keep consistency. Just edit gradle.properties file and add lines:

    ANDROID_BUILD_MIN_SDK_VERSION=14
    ANDROID_BUILD_TARGET_SDK_VERSION=21
    ANDROID_BUILD_TOOLS_VERSION=21.1.3
    ANDROID_BUILD_SDK_VERSION=21
    

    Now you can use it in your build.gradle files (in app and libraries modules) like below:

    //...
    android {
        compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
        buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
    
        defaultConfig {
            minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
            targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        }
    }
    //...
    
  3. That’s all. Just click‚ synchronise the project with the Gradle’ icon synchronise with Gradle. Your library should be available in your project.

Google I/O 2013 - The New Android SDK Build System is a great presentation about building Android apps with Gradle Build System: As Xavier Ducrohet said:

Android Studio is all about editing, and debugging and profiling. It's not about building any more.

At the beginning it may be little bit confusing (especially for those, who works with Eclipse and have never seen the ant - like me ;) ), but at the end Gradle gives us some great opportunities and it worth to learn this build system.

csdnceshi61
derek5. My project correpted thanks :) Error:(64, 0) No such property: sonatypeUsername for class: org.gradle.api.internal.project.DefaultProject_Decorated <a href="openFile">Open File</a>
大约 5 年之前 回复
csdnceshi73
喵-见缝插针 Error:Configuration with name 'default' not found...
大约 5 年之前 回复
weixin_41568127
?yb? Try this instead on 5/5.1 project(':PagerSlidingTabStrip').projectDir = new File('app/libs/PagerSlidingTabStrip') for example
5 年多之前 回复
csdnceshi62
csdnceshi62 fantastic guide !
5 年多之前 回复
csdnceshi67
bug^君 Both step 5 and 5.1 don't work
5 年多之前 回复
csdnceshi64
游.程 The library must be unzipped?
5 年多之前 回复
csdnceshi75
衫裤跑路 I tried both 5 and 5.1 and in both cases i got the error: Error:Configuration with name 'default' not found. It is not working for me :/ @froger_mcs
5 年多之前 回复
weixin_41568196
撒拉嘿哟木头 No difference for the final effect, but doing it in the gradle-way can help you to better understand app building.
接近 6 年之前 回复
weixin_41568174
from.. This is a long comment thread but I felt it makes more sense to ask my question here. This answer and the answer below it accomplish the same goal. Which makes more sense assuming its not a maven repo? Should I do it with gradle? Or should i use the intellij type way?
接近 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 Have you added /libs directory in your project root like is described in 4th step?
接近 6 年之前 回复
csdnceshi68
local-host Can anyone help me for below issue, No signature of method: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.compile() is applicable for argument types: (org.gradle.api.internal.file.collections.DefaultConfigurableFileTree) values: [directory 'libs'] Possible solutions: module(java.lang.Object)
接近 6 年之前 回复
csdnceshi70
笑故挽风 Everyone will benefit if you can explain the same using screen shots....!!!!
接近 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 You were right. I've just updated my answer to the newest Android Studio (1.0) version.
接近 6 年之前 回复
csdnceshi59
ℙℕℤℝ This answer is not up to date with the current Android Studio version.
接近 6 年之前 回复
weixin_41568184
叼花硬汉 how to delete Actionbarsherlock module delete android-support-library,where is the location?
6 年多之前 回复
csdnceshi63
elliott.david Import Module option is missing!!
6 年多之前 回复
csdnceshi71
Memor.の I have the same question as @ffleandro said. In current project structure, each application project contains one copy of the library project, how to use single library project in multiple application projects?
接近 7 年之前 回复
weixin_41568134
MAO-EYE Why dont i have "Import Module" section, at the option where you direct us ? I'm using Android Studio 0.3.1
接近 7 年之前 回复
csdnceshi58
Didn"t forge Where is Global libraries (#10: "now go to Global libraries")? Other than that, it works as described :) Thanks so much. (I hope Google will get down to it - such a simple task is headscratchingly complex at the moment)
大约 7 年之前 回复
csdnceshi77
狐狸.fox I can't find the sherlock library project after i copy it to the libraries folder. when I try to import a module.
7 年多之前 回复
csdnceshi53
Lotus@ why don't you put the sample code into a github repo? it would make life easier, and potentially clarify some confusion.
7 年多之前 回复
csdnceshi53
Lotus@ tried and tried.. just kept on getting this error: Gradle: A problem occurred configuring project ':HelloWorld'. > Failed to notify project evaluation listener. > Configuration with name 'default' not found. i also tried suggestions by @victorn. and akbar ibrahim.. still didn't work for me
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 you are right. Including support library in two projects is bad practise. Here you have good answer how to add support library into two or more projects: stackoverflow.com/a/16746682/2021293
7 年多之前 回复
csdnceshi69
YaoRaoLov In your solution, my libraries need to be inside my project structure. What if I want to use a Library Project as dependency in several projects? How do I add to my gradle an external module dependency?
7 年多之前 回复
csdnceshi54
hurriedly% +1. Was struggling with this for a long time. As victor n said, referencing the main project's support jar from actionbarsherlock module doesn't work. I had to do the following to get it working... (1) Remove compile files('libs/android-support-v4.jar') from the project's build.gradle. The main module should only have compile project(":libraries:actionbarsherlock"). (2) Add compile files('libs/android-support-v4.jar') instead of compile files(':HelloWorld/libs/android-support-v4.jar') in actionbarsherlock's build.gradle.
7 年多之前 回复
csdnceshi76
斗士狗 hey there, you perfectly explained the real issue. voting up your answer so other people can see it. one minor thing that didn't work on my side is referencing the support library in the dependency's build.gradle. as it turns out ':Project/libs...' did not work for some reason. i had to do away with the project identification. so 'libs/...'. and it compiled fine. one note is that these two ways of referencing paths or projects is confusing. i hope a simple and unified scheme comes up in the future. there is no reason why the original solution wouldn't work.
7 年多之前 回复

Here is the visual guide:

Update for Android Studio 0.8.2:

In Android Studio 0.8.2, go to Project Structure -> under Modules just hit the plus button and select Import Existing Project and import actionbarsherlock. Then synchronise your Gradle files.

If you face the error

Error: The SDK Build Tools revision (xx.x.x) is too low. Minimum required is yy.y.y

just open the build.gradle file in actionbarsherlock directory and update the buildToolsVersion to the suggested one.

android {
  compileSdkVersion 19
  buildToolsVersion 'yy.y.y'

Android Studio 0.8.2


Menu File -> Project Structure...:

First

Module -> Import Module

Second

After importing the library module, select your project module and add the dependency:

Third

And then select the imported module:

Forth

csdnceshi79
python小菜 It was way back during beta days of Android studio 0.4.3. As for accession 3rd party repo, id say, avoid using +. Just specify the version u want. If u still cant trust it enough, u can create a jar(or clone) of any repo and use it.
接近 5 年之前 回复
csdnceshi52
妄徒之命 are... are you from the future? But seriously, they need to make this simple like it was in Eclipse ADT; who wants to hit a third-party repo and compile (potentially) arbitrary code into each build? That seriously undermines QA and code-freeze protocols
接近 5 年之前 回复
csdnceshi63
elliott.david This will copy the library module in your project, which is not what you want if you want a common code base shared between several projects
大约 6 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 The key for me to make this work and resolve the package not found errors was the step Select your project module and add dependency dependencies { // ... compile project(':library') }
大约 6 年之前 回复
csdnceshi79
python小菜 Import module option not available in Android Studio4.3
6 年多之前 回复

Use menu File -> Project Structure -> Modules.

I started using it today. It is a bit different.

For Sherlock, maybe you want to delete their test directory, or add the junit.jar file to the classpath.

To import the library using gradle, you can have to add it to the dependencies section of your build.gradle (the module's one).

E.g.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.0'
    compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
}

Android Studio is changing.

There exist a section named "Open module settings" if you right-click on a module folder in the project section of Android Studio (I'm using the version 0.2.10).

csdnceshi51
旧行李 Looks like it was fixed in 0.8.2
大约 6 年之前 回复
csdnceshi54
hurriedly% I'm using version 0.5.8 and in File > Project Structure > Modules is a sub-menu, but I can't right click on it and there's nothing close to Module Settings or anything. There is a tab called Dependencies, where I suppose you set the build path. Can anyone clarify?
6 年多之前 回复
csdnceshi77
狐狸.fox I find out that exist a section named "Open module settings" if you right-click on a module folder in the project section of android studio (I'm using the version 0.2.10)
大约 7 年之前 回复
csdnceshi63
elliott.david On Android Studio 0.2.8 there is no Modules section in the Project Structure window.
大约 7 年之前 回复
csdnceshi65
larry*wei Try this: Compile project. Click on error. A light bulb button hovers over the error line. Click it and select the desired action (like "add to class-path") to fix the problem.
7 年多之前 回复
csdnceshi61
derek5. FYI on the first update Google pushed to AS this week, the Project UI is now gone and a message dialog is in its place telling the user to edit the gradle files directly.
7 年多之前 回复
weixin_41568208
北城已荒凉 This is not advisable way as this doesn't write back changes to your build.gradle file at moment. We should edit build.gradle file directly as i mentioned in my answer below.
7 年多之前 回复
csdnceshi79
python小菜 Check my answer, it may solve your problem. ABS may be compiled as an application project instead of a library project.
7 年多之前 回复
csdnceshi70
笑故挽风 and fish, see my answer below. I had the same problem as you and fixed it by adding the sherlock module as a dependency to my main app module.
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 Hi, I've the same problem like Alex ("Gradle: Error retrieving parent for item: No resource found that matches the given name 'Theme.Sherlock.Light'.") - the Java dependency seems to be solved correctly, cause the IDE doesn't blame my SherlockActivity, but for some reason Gradle doesn't seem to look into the ressources of ABS. Any ideas?
7 年多之前 回复
csdnceshi51
旧行李 under MyProject I ve Android 4.2.2 and the Sherlock dependecies. How does your looks like?
7 年多之前 回复
csdnceshi51
旧行李 next to the run button, there is a label with Android. If you ckick there you will find Edit Configuration. Push and under Target Device click on "Show Chooser Dialg"
7 年多之前 回复
csdnceshi51
旧行李 Under the Sherlock Module -> Dependecies I have android 4.2.2 and the support Library v4
7 年多之前 回复
weixin_41568183
零零乙 Hmm it still says android-apt-compiler: styles.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'Theme.Sherlock.Light.DarkActionBar'.
7 年多之前 回复

I have just found an easier way (rather than writing directly into the .gradle files).

This is for Android Studio 1.1.0.

  1. Menu File -> New Module...:

    Import Existing Project

    Click on "Import Existing Project".

  2. Select the desired library and the desired module.

  3. Click finish. Android Studio will import the library into your project. It will sync gradle files.

  4. Add the imported module to your project's dependencies.

    Right click on the app folder -> Open Module settings -> go to the dependencies tab -> Click on the '+' button -> click on Module Dependency.

    The library module will be then added to the project's dependencies.

    Add library module

  5. ???

  6. Profit

weixin_41568196
撒拉嘿哟木头 But what's step 5?! :-D
大约 2 年之前 回复

You can do this easily. Go to menu File -> New -> Import Module...:

Enter image description here

Browse for the directory which contains the module. Click Finish:

Enter image description here

Go to Project Structure and add Module Dependency:

Enter image description here

Note: If you receive an SDK error, update that one.

Editing library dependencies through the GUI is not advisable as that doesn't write those changes to your build.gradle file. So your project will not build from the command-line. We should edit the build.gradle file directly as follows.

For instance, given to following structure:

MyProject/

  • app/
  • libraries/
    • lib1/
    • lib2/

We can identify three projects. Gradle will reference them with the following names:

  1. :app
  2. :libraries:lib1
  3. :libraries:lib2

The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:

dependencies {
    compile project(':libraries:lib1')
}
weixin_41568196
撒拉嘿哟木头 As editing through GUI doesn't writes those changes to your build.gradle file. GUI editing only saves changes in IntelliJ's own project data. This is a bug at the moment which will be fixed in future releases. You can refer to this answer from Google Android-Studio Team Lead stackoverflow.com/questions/16678447/…
7 年多之前 回复
weixin_41568131
10.24 Really? Strange, they have the whole GUI and yet it's not advisable. How so?
7 年多之前 回复

Android Studio 3.0

Just add the library name to the dependencies block of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.example:some-library:1.0.0'
}

Note that you should use implementation rather than compile now. This is new with Android Studio 3.0. See this Q&A for an explanation of the difference.

csdnceshi80
胖鸭 It's actually a change in Gradle 4, not Android Studio 3. You can continue to use com.android.tools.build:gradle:2.3.3 instead of 3.0.0 in Android Studio 3 if you want to continue using "compile".
接近 3 年之前 回复

Open the build gradle module app file and add your dependency. If you download the library, just import and build as gradle.

Otherwise add repositories in side gradle module app:

repositories {
        maven { url 'http://clinker.47deg.com/nexus/content/groups/public' }
}

The first repositories will download the library for you.

And compile the downloaded library:

 compile ('com.fortysevendeg.swipelistview:swipelistview:1.0-SNAPSHOT@aar') {
        transitive = true
    }

If you are creating a library, you just need to import the project as import new module.

For Android Studio:

Enter image description here

Click on Build.gradle (module: app).

And add for

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/commons-io-2.4.jar')
}

and in your directory "app", create a directory, "libs". Add the file yourfile.jar:

Enter image description here

Finally, compile the Gradle Files:

Enter image description here

weixin_41568184
叼花硬汉 dude respect :D
4 年多之前 回复

I would consider Dependencies, Android Libraries and Multi-project setup necessary reading. Please take a few minutes to do so.

Particularly, in the case of a non-jar library project, read the following snippet from above source:

Gradle projects can also depend on other gradle projects by using a multi-project setup. A multi-project setup usually works by having all the projects as sub folders of a given root project.

For instance, given to following structure:

MyProject/
 + app/
 + libraries/
    + lib1/
    + lib2/

We can identify 3 projects. Gradle will reference them with the following name:

:app
:libraries:lib1
:libraries:lib2

Each projects will have its own build.gradle declaring how it gets built. Additionally, there will be a file called settings.gradle at the root declaring the projects. This gives the following structure:

MyProject/
 | settings.gradle
 + app/
    | build.gradle
 + libraries/
    + lib1/
       | build.gradle
    + lib2/
       | build.gradle

The content of settings.gradle is very simple:

include ':app', ':libraries:lib1', ':libraries:lib2'

This defines which folder is actually a Gradle project.

The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:

dependencies {
    compile project(':libraries:lib1')
}

Kindly note that there was little or no use of Android Studio GUI to make this happen.

I am currently using git submodules to link the nested library to the actual library git repo to avoid a dependency mess.

csdnceshi64
游.程 Thanks for the git submodules tip. I was using junction before, but have now switched to SVN externals. Works like a charm.
5 年多之前 回复
csdnceshi56
lrony* thank you so much for including the only answer that makes sense. every other answer is outdated and just doesn't work. i didn't even try in CS at Virginia Tech because the whole first two years was learning to fckn click around in eclipse. it didn't make any fckn sense, but seeing the gradle result of random clicks in an IDE does.
6 年多之前 回复
csdnceshi80
胖鸭 Very helpful and, more importantly, not play to the gui whims of the day.
6 年多之前 回复
csdnceshi70
笑故挽风 Kindly upvote if you found this helpful, so that others can avoid the pain and move along faster.
大约 7 年之前 回复
共30条数据 1 3 尾页
立即提问
相关内容推荐