Android:无法在非静态方法中设置 getContext() - 需要 API 级别 23

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

下面是一些从非静态方法调用的源代码。我收到错误

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

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

如何获取上下文对象?

在对象资源管理器 > Gradle 脚本 > build.gradle 下,我看到了这个。对我来说看起来像版本 23。我在寻找正确的位置吗?

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'
}

我好像有 Android Studio 1.5.1。我刚刚在 Android Studio 中选择了 SettingsActivity 项目模板。并在该默认代码中添加了一个 class。

您需要导入 import android.support.v4.app.Fragment 而不是 import android.support.app.Fragment;

一种解决方法是在 Activity onCreate 方法中将 "this" (activity) 转换为 (Context)。

传递 getActivity() 而不是 getContext() 作为上下文。