【问题标题】:How to import class from another module in android studio?如何从android studio中的另一个模块导入类?
【发布时间】:2016-03-28 23:03:34
【问题描述】:

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

  1. 模块 x 有一个类 Egg(包:com.example.x)
  2. 模块 y 有一个类 Foo(包:com.example.y)

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

Import com.example.y.Foo;

现在,Foo 无法被 android 识别。

问题,

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

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

或者解决办法可能是别的。

【问题讨论】:

  • Foo 是公开的吗?并且i 应该在import 中小写。
  • 你是否将该模块添加到 gradle 文件中的依赖项中?
  • @prerakSola 是的 Foo 是公开的,而 i 很小。
  • 能否在您的问题中添加这两个类的代码?
  • @prudhvi 不,我没有将模块添加到依赖项。我会尝试然后告诉你。

标签: java android android-studio


【解决方案1】:

确保以下几点:

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

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

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

【讨论】:

  • 确保使用 Android 库创建模块 y 或将 gradle 文件中的“apply plugin: 'com.android.application'”替换为“apply plugin: 'com.android.library'”。跨度>
  • 如何从我的另一个模块中引用我的代码?我的意思是我有一个moduleA,我在其中使用moduleB,而moduleB 使用第三个moduleC,但是当我在moduleA 中引用moduleC 中的一个类时@(控制+点击)它向我展示了编译后的@ 987654329@ 而不是我的.java 课程来自我的moduleC。你有什么想法来解决这个问题吗?谢谢!
【解决方案2】:

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

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

【讨论】:

  • 我只能将此解决方案应用于库模块
【解决方案3】:

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

implementation project(':y')

compile project() - 已弃用且不再有效

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

【讨论】:

    猜你喜欢
    • 2016-06-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多