Java 如何从android studio中的另一个模块导入类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34419962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:37:53  来源:igfitidea点击:

How to import class from another module in android studio?

javaandroidandroid-studio

提问by Palak

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

我在单个 android 项目中创建了两个模块,将其命名为 x 和 y。

  1. Module x has a class Egg (Package: com.example.x)
  2. Module y has a class Foo (Package: com.example.y)
  1. 模块 x 有一个类 Egg(包:com.example.x)
  2. 模块 y 有一个 Foo 类(包: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

现在我想在类Egg中导入类Foo,为此我在类Egg中写了下面提到的语句

Import com.example.y.Foo;

Now, Foo is not recognized by android.

现在,Android 无法识别 Foo。

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?

是否可以仅使用 import 语句从不同的模块导入 Class?

我是否需要创建模块 y 的库,然后将创建的库导入模块 x?

Or may the solution is something else.

或者可能解决方案是别的。

采纳答案by pdegand59

Make sure of the following:

请确保以下几点:

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

在settings.gradle,你应该有:include ':x', ':y'

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

在 x/build.gradle 中,您应该添加 y 作为依赖项:

dependencies {
        compile project(':y')
        // other dependencies
}

回答by felhi

now when create new module,settings.gradle add automatically this module.after that u should add this line:

现在当创建新模块时,settings.gradle 会自动添加这个模块。之后你应该添加这一行:

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

回答by Daniel

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

结合并更正之前的两个答案,最好的解决方案是将这一行添加到 x/build.gradle -> dependencies

implementation project(':y')

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

compile project()- 已弃用,不再工作

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

如果您只想实现单个模块,则无需使用implementation(..., .., project(":y")结构。