Android: Unable to set getContext() in non-static method - requires API Level 23

淺唱寂寞╮ 提交于 2019-12-08 03:06:34

问题


Below, is some source code which is being called from a non-static method. I'm getting the error

"Call requires API level 23 (current min is 15); android.app.Fragment#getContext"

android.content.Context context = (Context) getContext();

How can I get the context object?

Under the object explorer > Gradle Scripts > build.gradle, I see this. Looks like version 23 to me. Am I looking in the correct location?

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.test.test"
        minSdkVersion 15
        targetSdkVersion 23
        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:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
}

Looks like I have Android Studio 1.5.1. I just chose the SettingsActivity project template in Android Studio. And added one class to that default code.


回答1:


You need to import import android.support.v4.app.Fragment instead of import android.support.app.Fragment;




回答2:


Pass getActivity() instead of getContext() as Context.




回答3:


One way to solve was to cast "this" (activity) to (Context) inside the Activity onCreate method.



来源:https://stackoverflow.com/questions/36736244/android-unable-to-set-getcontext-in-non-static-method-requires-api-level-23

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!