Android studio报错:Could not find method compile() for arguments 问题的两种解决方法
问题全称:
Could not find method compile() for arguments [directory ‘libs’] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
如图:
引发问题原因为:
在android studio 3.0 版本之前,第三方库或者module的依赖方式有compile、implementation。
android studio 3.0 版本之后,compile被取代,改用API dependency,实质完全等同于compile。
解决方法1:
将 compile 改为 implementation 即可,如图:
解决方法2:
将 compile 改为 api 即可,如图:
dependencies依赖api、compile和implementation的区别:
一、依赖变化
当我们使用Android Studio3.X新建项目时会发现,默认的依赖由之前的compile更改为implementation了。
3.0 以下版本build.gradle中依赖的写法:
compile fileTree(dir: 'libs', include: ['*.jar'])
1
但在3.0后的写法为
implementation fileTree(dir: 'libs', include: ['*.jar'])
或
api fileTree(dir: 'libs', include: ['*.jar'])
二、区别
在3.X版本中,compile 指令被标注为过时方法,而新增了两个依赖指令,一个是implementation和api,这两个都可以进行依赖添加,但是有什么区别呢?
api
完全等同于compile指令,没区别,你将所有的compile改成api,完全没有错。
implementation
这个指令的特点就是,对于使用了该命令编译的依赖,对该项目有依赖的项目将无法访问到使用该命令编译的依赖中的任何程序,也就是将该依赖隐藏在内部,而不对外部公开。
示例
比如我在一个library中使用implementation依赖了gson库,然后我的主项目依赖了library,那么,我的主项目就无法访问gson库中的方法。这样的好处是编译速度会加快,推荐使用implementation的方式去依赖,如果你需要提供给外部访问,那么就只能使用api方式了。
在Google IO相关话题的中提到了一个建议,就是依赖首先应该设置为implementation的,如果没有错,那就用implementation,如果有错,那么使用api指令,这样会使编译速度增快。
如果对你有帮助,就一键三连呗(点赞+收藏+关注),我会持续更新更多干货~~