55

I created two modules in single android project, named it x and y.

  1. Module x has a class Egg (Package: com.example.x)
  2. Module y has a class Foo (Package: com.example.y)

Now I want to import class Foo in the class Egg, for which I wrote the statement mentioned below in class Egg

Import com.example.y.Foo;

Now, Foo is not recognized by android.

Questions,

Is it possible to import Class from a different module using just import statement?

Do I need to create library of Module y and then import created library into module x?

Or may the solution is something else.

Palak
  • 1,276
  • 4
  • 17
  • 24

3 Answers3

99

Make sure of the following:

In settings.gradle, you should have: include ':x', ':y'.

In x/build.gradle, you should add y as a dependency:

dependencies {
        compile project(':y')
        // other dependencies
}
sagix
  • 600
  • 1
  • 4
  • 15
pdegand59
  • 12,776
  • 8
  • 51
  • 58
  • 4
    Make sure of creating Module y with Android Library or replace " apply plugin: 'com.android.application' "with " apply plugin: 'com.android.library' " in gradle file. – user3269713 Apr 13 '16 at 03:31
  • How can I refer my code from another of my modules? I mean I have a `moduleA` where I use `moduleB` and `moduleB` uses a third `moduleC` but when I refer a class from `moduleC` in `moduleA` (control + click) it is showing me the compiled `.class` instead of my `.java` class from my `moduleC`. Do you have some idea to solve this? Thanks! – epool Jul 05 '16 at 19:49
  • 'compile' is deprecated; use 'implementation'. And this goes into app build.gradle, not the module's build.gradle. – steve May 23 '23 at 14:55
13

Now when you create new module,the settings.gradle file add automatically this module.After that u should add this line:

    dependencies {
    implementation(
    ...,
    ..,
            project(":y")
)
}
10

Combining and correcting two previous answers the best solution is to add this single line to x/build.gradle -> dependencies

implementation project(':y')

compile project() - is deprecated and won't work anymore

If you want to implement just a single module there is no need to use implementation(..., .., project(":y") structure.

Daniel
  • 2,415
  • 3
  • 24
  • 34