2016-02-04 17 views
0

我只是使用菜單來創建新片段,並且默認情況下它會向片段生成文件拋出錯誤,我沒有添加任何代碼。問題是在onAttach()方法在Android App上的compileSdkVersion 22上創建新片段時出錯:onAttach()方法失敗

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    if (context instanceof OnFragmentInteractionListener) { 
     mListener = (OnFragmentInteractionListener) context; 
    } else { 
     throw new RuntimeException(context.toString() 
       + " must implement OnFragmentInteractionListener"); 
    } 
} 

它說: 「onAttach(android.app.Activity)的片段不能被應用到(android.content.Context)」

我進口在片段文件:

import android.content.Context; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

我gradle這個文件:

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 22 
    buildToolsVersion "22.0.1" 

    defaultConfig { 
     applicationId "license.j4ftech.com.mapevents" 
     minSdkVersion 19 
     targetSdkVersion 22 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    testCompile 'junit:junit:4.12' 
    compile 'com.android.support:appcompat-v7:22.2.0' 
    compile 'com.android.support:design:22.2.0' 
    compile 'de.hdodenhof:circleimageview:2.0.0' 
    compile 'com.android.support:support-v4:22.2.0' 
} 

我的gradle文件:

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 22 
    buildToolsVersion "22.0.1" 

    defaultConfig { 
     applicationId "license.j4ftech.com.mapevents" 
     minSdkVersion 19 
     targetSdkVersion 22 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    testCompile 'junit:junit:4.12' 
    compile 'com.android.support:appcompat-v7:22.2.0' 
    compile 'com.android.support:design:22.2.0' 
    compile 'de.hdodenhof:circleimageview:2.0.0' 
    compile 'com.android.support:support-v4:22.2.0' 
} 

我該如何解決這個問題?

回答

3

onAttach(上下文上下文)方法是在API級別23中引入的。您的編譯/目標SDK版本是22,這就是項目無法找到方法定義的原因。您可以切換回onAttach(Activity a)使用舊的棄用方法,或將appcompat版本更改爲最新版本(23.1.1)以使用新方法。

使用最新的支持庫:

compile 'com.android.support:appcompat-v7:23.1.1' 
compile 'com.android.support:design:23.1.1' 

在gradle這個文件,並設置compileSdkVersion/targetSdkVersion至23

+0

謝謝,我只是更新到API 23以防萬一.....我不希望被棄用的方法...謝謝,我會在5分鐘內將你的答案標記爲 – JAF

+0

,安裝更新後哪些值應該在gradle文件中從22更改爲23? – JAF

+1

我剛編輯我的答案:)。另外,請刪除支持v4依賴項。你不需要它,因爲默認情況下,appcompat v7會添加它。 – androholic

相關問題