在 gradle Android Studio 中找不到方法 compile()

Could not found method compile() in gradle Android Studio

我是 Android Studio 和 android 开发的新手,正在开发我的第一个应用程序。

我想用CarViewRecyclerView来显示数据。根据很多教程,我需要添加以下依赖项

compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'

我的build.gradle就是这样

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

dependencies {
    compile 'com.android.support:cardview-v7:21.0.+'
    compile 'com.android.support:recyclerview-v7:21.0.+'
}

但是在同步 gradle 时,它给出了错误

Error:Could not find method compile() for arguments [com.android.support:cardview-v7:21.0.+] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Please install the Android Support Repository from the Android SDK Manager.

我尝试了 Google 搜索中的许多解决方案,但找不到任何有效的解决方案。

如错误所述,您必须从 sdk 管理器下载并安装 Android 支持存储库。

为此,请转到 Android Studio 工具栏,单击工具 > Android > SDK 管理器。 单击 SDK Tools 选项卡,搜索 Support Repository 并选中 Android Support Repository 和 Google Repository。

点击应用按钮,等待存储库下载和安装。完成后,关闭 SDK 管理器并再次尝试同步 Gradle。

而且,如@cricket_007 所说,将您的依赖项移动到 build.gradle (Module: ..) 文件。
您还可以通过转到文件 > 项目结构(或按 Ctrl + Shift + Alt + S)、模块下方的选项(可能名为 app)、选项卡 Dependencies 并按绿色 +按钮。

Android Studio 创建了一个包含两个 build.gradle 文件的项目。

这段代码

dependencies {
    compile 'com.android.support:cardview-v7:21.0.+'
    compile 'com.android.support:recyclerview-v7:21.0.+'
}

进入项目的app/build.gradle。您还想将 21 版本号更新为您正在编译的 SDK。

在那之后,你还必须install the Android Support Repository from the Android SDK Manager.