Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決 Android Studio 報錯 Failed to find: com.android.support:appcompat-v7

編輯:關於 Android 程式設計

錯誤訊息

Error: Failed to find: com.android.support:appcompat-v7:21.+
Install Repository and sync project

打開別人的專案時經常遇到。它看起來像依賴缺失,實際原因往往是專案結構沒被 Gradle 正確辨識,導致 appcompat 宣告所在的 build 檔案沒被讀取。

步驟一:確認 build.gradle 的位置

先看 Gradle Scripts 底下有沒有 build.gradle (Module: app)。如果沒有,就把 build.gradle (Project: ...) 裡的這段暫時屏蔽掉:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/pushservice-4.5.3.48.jar')
    compile 'com.android.support:appcompat-v7:22.2.1'
}

然後 Rebuild。等專案結構被正確解析、build.gradle (Module: app) 出現之後,再回頭修改裡面的內容。

步驟二:對齊 SDK 版本

android {
    compileSdkVersion 22        // 依 SDK Manager 中已安裝的版本設定
    buildToolsVersion "22.0.1"  // 依已安裝的 build-tools 設定

    defaultConfig {
        applicationId "com.example.zhonghang.mypushdemo"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                          'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/pushservice-4.5.3.48.jar')
    compile 'com.android.support:appcompat-v7:22.2.1'
}

重點是 compileSdkVersion 與 buildToolsVersion 必須對得上本機 SDK Manager 裡實際安裝的版本,而 appcompat 的版本號也不能高於 compileSdkVersion。

步驟三:手動掛上 appcompat

依序點選 File → Project Structure → 選中要開啟的專案 → Dependencies → 右側加號 → 第一個選項,然後搜尋 appcompat 並加入。

完成後 Rebuild

操作完再 Rebuild 一次,專案就能正常開啟了。

補充:更常見的替代解法

如果上述流程走完還是失敗,多半是真的沒安裝對應版本的 Support Repository。此時有兩條路:

  • 開啟 SDK Manager,勾選 Android Support Repository 與對應 API Level 的 Android Support Library 安裝,再 Sync。
  • 把專案中的 appcompat 版本改成 21.+ 之外的、本機確實存在的版本(例如統一改成 22.2.1),避免用 + 這種浮動寫法——浮動版本在離線或網路受限環境下特別容易解析失敗。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved