2016-02-04 16 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

相关问题